1 of 114

STRUCTURED QUERY LANGUAGE

2 of 114

DATABASE CONCEPTS

  • A collection of data in table form is called as database.

  • A database may be referred to as a collection of interrelated data stored together to serve multiple applications such as adding, deleting and manipulating the data.

  • A database management system is a software that provide centralized control over the data.

3 of 114

SQL ENABLES THE FOLLOWING:

  1. Creating/ modifying a database structure
  2. Changing security settings for systems.
  3. Permitting users for working on databases or tables.
  4. Querying databases
  5. Inserting/ Modifying/Deleting the database contents.

4 of 114

MAIN PURPOSE OF DATABASE

  • Reduces data redundancy:

Duplication of data is known as data redundancy. That means multiple copies of the same data is available in many places.

  • Database can control data inconsistency:

Suppose multiple copies of the same data is available in many places, but only one copy of the data is updated, and the other copies has the old data. This situation is referred to as inconsistency of data.

Multiple mismatching of the same data is known as data inconsistency.

  • Sharing of data :

Since data is available in centralized form, data may be shared among several users, in the sense that each users may use the same data for different purpose.

5 of 114

MAIN PURPOSE OF DATABASE

  • Data security :

Refers to protection of data against accidental or intentional disclosure unauthorized persons for modification or destruction.

  • Database enforce standards:

DBMS can ensure that all the data follow a certain standard.(refers to the format in which the data is stored or accessed).

  • Privacy of Data :

refers to the rights of individuals and organizations to determine when, how and to what extend information about them can be transmitted to others.

6 of 114

LEVEL OF DATABASE IMPLEMENTATION

  1. Internal or physical level: refers to how the data is actually stored, it is the lowest level of data abstraction.

  • Conceptual level: describes what data are actually stored in a database. It also describes the relationships between existing data.

  • External or view level: It is concerned with the way in which the data are viewed by the individual user.

7 of 114

Internal level

Stored item length :40B

Name type(Where it is stored)

Price type

Qty type

Conceptual level

Name char(40)

Price Numeric

Qty Numeric

View 1

Name + Price

View 2

Price+Qty

8 of 114

DATABASE TERMINOLOGY

  • Relation:

A relation is a table in database i.e data is arranged in rows and columns.

A relationship has the following property

  1. In any given column, all the items are of same kind(same data type).
  2. All rows of a relation are distinct.

SpNo

ship

1

abc

2

xyz

3

def

9 of 114

DATABASE TERMINOLOGY

  • Domain :

A domain is a pool of values from which the actual values are drawn.

S1 S2 S3 S4 S5

SpNo

ship

S1

abc

S3

def

SpNo

city

S1

Jaipur

S3

chennai

S4

Delhi

Domain

10 of 114

DATABASE TERMINOLOGY

  • Tuples : A rows in the table is called as tuple, also known as records.(RT)

  • Attribute : The columns/Fields in a table is called as Attribute.(Ca).

  • DEGREE : The number of attributes in a relation is referred to as degree.(CAD)

  • CARDINALITY : The number of tuples in a relation is known as cardinality(RTC).

  • A view is a virtual table that does not really exist on its own but is derived from one or more base tables.

11 of 114

RNO

NAME

MARKS

DOB

GRADE

1

AAAA

89

1/2/2000

B

2

BBBB

75

5/12/2000

C

3

CCCC

96

4/5/1999

A

4

DDDD

69

8/9/2000

D

ATTRIBUTE

TUPLE

DEGREE : 5

CARDINALITY : 4

12 of 114

KEYS

  • PRIMARY KEY:

A Primary key is a unique attribute in a relation. It can be a set of one or more attribute that can uniquely identify the tuples within the relation.

  • CANDIDATE KEY:

All the attributes in a relation that can serve as a primary key is known as candidate key.

  • ALTERNATE KEY:

A candidate key that is not the primary key is called an alternate key.

13 of 114

KEYS

  • FOREIGN KEY

An attribute whose values are derived from the primary key of some other table is known as foreign key in its current table.

14 of 114

REFERENTIAL INTEGRITY

  • Referential Integrity is a system of rules that a DBMS uses to ensure that relationships between records in related tables are valid and that users don’t accidently delete or change related data.

  • You can set referential integrity when all of the following conditions are met:
  • The matching field from the primary table is a primary key or has a unique value.
  • The related fields must have the same data type.
  • Both the tables should belong to the same database.

15 of 114

KEY FEATURES OF MYSQL

  • Speed
  • Ease to use
  • Free of cost
  • Portability
  • Security
  • Data types

16 of 114

  • CANDIDATE KEYS

RNO,AdminNo,NAME

  • PRIMARY KEYS

AdminNo

  • ALTERNATE KEYS

RNO,NAME

RNO

AdminNo

NAME

MARKS

DOB

GRADE

1

121

AAAA

89

1/2/2000

B

2

122

BBBB

75

5/12/2000

C

3

123

CCCC

96

4/5/1999

A

4

124

DDDD

69

8/9/2000

D

5

125

EEEEE

92

23/6/2000

A

17 of 114

RULES FOR SQL COMMANDS

  • SQL statements are not case sensitive
  • SQL statements can be executed on one or more tables
  • Keywords cannot be abbreviated
  • Place a semi-colon at the end of the last clause

18 of 114

MYSQL SQL ELEMENTS

  • The basic elements are
  • Literals
  • Datatypes
  • Nulls
  • Comments

19 of 114

LITERALS

  • Literals refers to a fixed data value.
  • This fixed data value may be of character type or numeric literals.
  • “Computer” , “XI-A” are all character literal
  • 22,18,2021 are all numeric literal.

20 of 114

DATA TYPES

  • MySQL uses many data type divided into three categories:

🡪 Numeric

🡪 Date and Time

🡪 String types

21 of 114

DATA TYPES IN SQL

  • char
  • varchar
  • tinytext
  • text

  • int
  • smallint
  • numeric
  • decimal
  • float
  • real
  • double
  • number

  • date
  • time
  • boolean

22 of 114

DIFFERENCE BETWEEN CHAR AND VARCHAR

  • The difference between CHAR and VARCHAR is that of the fixed length and variable length.
  • The CHAR datatypes specifies a fixed length character string. When a column is given datatype as CHAR(n) ,then MySQL ensures that all values stored in that column have this length i.e n bytes. If a value is shorter than this length n then blanks are added, but the size of value remains n bytes.
  • VARCHAR, on the other hand specified variable length string. When a column is given datatype as VARCHAR(n) then the maximum size a value in this column can have is n bytes.

Each value that is stored in this column stores exactly as you specify it, i.e no blanks are added if the length is shorter than the maximum length n.

23 of 114

COMMENTS IN SQL

24 of 114

ACCESSING DATABASE IN MYSQL

  • First of all create a database

mysql>create database Name;

mysql>USE Name;

Database changed

25 of 114

CREATING A TABLE

  • A relation can be created in a database by CREATE TABLE statement in SQL

  • CREATE TABLE <table name>

( <attribute name> <data type> <size><constraint>,

<attribute name> <data type> <size><constraint>

);

26 of 114

TO CREATE A TABLE CALLED STUDENT WITH THE FOLLOWING ATTRIBUTE

  • CREATE TABLE STUDENT

( Rno int(3) PRIMARY KEY,

AdminNo int(3) NOT NULL UNIQUE,

Name char(20) NOT NULL,

Marks decimal,

School char(20) DEFAULT ‘BGS NPS’,

Grade char(2) );

RNO

AdminNo

NAME

MARKS

GRADE

27 of 114

TO CREATE A TABLE CALLED STUDENT WITH THE FOLLOWING ATTRIBUTE

  • CREATE TABLE STUDENT

( Rno int PRIMARY KEY,

AdminNo int NOT NULL,

Name char(20),

Marks decimal,

Grade char(2) );

RNO

AdminNo

NAME

MARKS

GRADE

28 of 114

ADD VALUES INTO THE TABLE

INSERT INTO STUDENT

VALUES (1,121,’AAA’,89,’B’);

  • If you want to insert only Rno, AdminNo and Name comand is

INSERT INTO STUDENT(RNO,AdminNo,NAME)

VALUES (1,121,’AAA’);

RNO

AdminNo

NAME

MARKS

GRADE

1

121

AAAA

89

B

2

122

BBBB

75

C

3

123

CCCC

96

A

29 of 114

INSERTING NULL VALUES

INSERT INTO STUDENT

VALUES (4,124,’DDD’,23,NULL)

Here, the Grade column for the forth record will be NULL

RNO

AdminNo

NAME

MARKS

GRADE

1

121

AAAA

89

B

2

122

BBBB

75

C

3

123

CCCC

96

A

30 of 114

VIEWING STRUCTURE OF A TABLE STUDENT

If you want to know the structure of a table, you can use Describe or Desc , the syntax is

mysql>DESC <TABLE NAME>;

mysql>DESC STUDENT;

RNO

AdminNo

NAME

MARKS

GRADE

1

121

AAAA

89

B

2

122

BBBB

75

C

3

123

CCCC

96

A

31 of 114

WRITE THE SQL QUERY TO CREATE A TABLE AND ADD THE FOLLOWING VALUES INTO THE TABLE.

Sno

Item

Qty

Price

Company

Supcode

City

1

Pen Drive

70

300

SanDisk

S109

Delhi

2

Camera

50

4500

CoolPix

S102

GOA

3

Laptop

100

35000

Lenovo

S112

Delhi

4

Car GPS

30

12000

Dell

S103

GOA

TABLE: SONY

32 of 114

SELECT- TO VIEW A TABLE

  • SELECT * FROM SONY;

To select the column Sno particular column

  • SELECT Sno from SONY;

To display Sno, Item Price from the same table

  • SELECT Sno, Item,Price from SONY;

33 of 114

WHERE

1. Query to display from table sony where price is 300.

  • SELECT * FROM SONY

WHERE Price=300;

2. Query to display the item name from table sony where price more than 5000.

  • SELECT Item FROM SONY

WHERE Price > 5000;

3. Query to display the item name and price from table sony where price more than 10000 and less than 40000.

  • SELECT Item,Price FROM SONY

WHERE Price > 10000 AND Price <40000;

34 of 114

CREATING A VIEW

  • A view is a kind of table whose contents are taken from other tables depending upon a condition. Views do not contain data on their own. Th contents of a view are determined by carrying out the execution of the given query.
  • A view is a (virtual) table that does not really exist in its own right but is instead derived from one or more underlying base table(s).

  • CREATE VIEW SONY_DUP AS

SELECT * FROM SONY

WHERE PRICE > 5000;

35 of 114

5. .Query to display from table sony where Supcode is S103.

  • SELECT * FROM SONY

WHERE Supcode=‘S103’;

6 .Query to display Item,Company from table sony where Supcode is S109.

  • SELECT Item,Company FROM SONY

WHERE Supcode=‘S109’;

7 .Query to display Item,Price,Company from table sony where Company is LENOVO or DELL.

  • SELECT Item,Company,Price FROM SONY

WHERE Company=‘LENOVO’ OR Company=‘DELL’;

36 of 114

MAX AND MIN

8. Query to display the maximum Price from table sony.

  • SELECT MAX(Price) FROM SONY;

9. Query to display the maximum Price from table sony from company Dell.

  • SELECT MAX(Price) FROM SONY

WHERE Compay=‘Dell’;

37 of 114

MAX AND MIN

12 Query to display the minimum Price from table sony.

  • SELECT MIN(Price) FROM SONY;

13. Query to display the minimum Price from table sony from company Dell.

  • SELECT MIN(Price) FROM SONY

WHERE Compay=‘Dell’;

38 of 114

AVERAGE

15. Display the average Price from the table SONY

  • SELECT AVG(Price) FROM SONY;

16 Display the average Price from the table SONY from DELL or LENOVO company.

  • SELECT AVG(Price) FROM SONY

WHERE Company=‘Dell’ OR Company=‘Lenovo’;

39 of 114

ORDER BY- TO ARRANGE IN ASC OR DESC ORDER ACCORDING TO AN ATTRIBUTE

17. Query to display according to the ascending order of Price from table sony.

  • SELECT * FROM SONY

ORDER BY Price ASC;

18. Query to display according to the Descending order of the Qty from table sony.

  • SELECT * FROM SONY

ORDER BY Qty DESC;

40 of 114

DISTINCT

  • Distinct keyword eliminates duplicate rows from the results of the SELECT statement.

SELECT DISTINCT City FROM SONY;

  • ALL keyword, Gives you all the results even retaining the duplicate output row.

SELECT ALL City FROM SONY;

City

Delhi

City

Delhi

Delhi

Delhi

Delhi

41 of 114

LOGICAL OPERATORS

  • Query to display name and marks from student table where grade is either A or B.

SELECT name, marks FROM student

WHERE grade=‘A’ OR grade=‘B’;

  • Query to display name and marks from student table where grade is A1 and marks greater than 90.

SELECT name, marks FROM student

WHERE grade=‘A’ AND marks>90;

  • Query to display name and marks from student table where grade is not C.

SELECT name, marks FROM student

WHERE NOT grade=‘C’;

42 of 114

BETWEEN

  • Query to display name and marks from student table where mark is between the range 55 to 75.

SELECT name, marks FROM student

WHERE marks>=55 AND marks<=75;

SELECT name, marks FROM student

WHERE marks between 55 AND 75;

//INCLUDING 55 AND 75

43 of 114

  • Query to display name from student table where Rno is not between 30 to 40.

SELECT name FROM student

WHERE RNo>=40 AND Rno <=30;

SELECT name, marks FROM student

WHERE NOT RNo between 30 AND 40;

44 of 114

CONDITION BASED ON LIST

  • To specify a list of values ,IN operator is used. The IN operator selects values that match any value in a given list of values.

  • Query to display the name of the student in class 5,8,11.

SELECT name FROM student

WHERE Class IN (5,8,11);

  • Query to display the name of the student not in class 5,8,11

SELECT name FROM student

WHERE Class NOT IN (5,8,11);

45 of 114

46 of 114

COUNT

  • To count the total number of rows in a table

SELECT COUNT(*) FROM SONY;

  • To count the number of records which are from company DELL

SELECT COUNT(*) FROM SONY

WHERE Company=‘DELL’;

  • Query to count the name of the student in class 5,8,11.

SELECT count (*) FROM student

WHERE Class IN (5,8,11);

  • To count the number of unique Company from the table SONY

SELECT COUNT(DISTINCT Company) FROM SONY;

47 of 114

USE OF % AND _

  • % 🡪 Represents a set of character

  • eg: TO list the names starting with letter A

select * from student

where name like ‘A%’;

  • List the members whose address will start with 13#

select * from student

where address like ’13#%’;

48 of 114

USE OF % AND _

  • _🡪 Represents a character

  • eg: TO list the names having 3 letter and starting with A

select * from student

where name like ‘A _ _’;

  • List the members name will end with D and having four letters

select * from student

where name like ’_ _ _ D’;

49 of 114

SEARCH FOR NULL

  • To display empno,empname fromEmployee table whose department is NULL

  • SELECT empno, empname FROM EMPLOYEE

WHERE department IS NULL;

50 of 114

HANDLING NULL

  • If you want to substitute NULL with a value in the output, you can use IFNULL() function.
  • SYNTAX
  • IFNULL(<Columnname>,value to be substituted)

SELECT NAME, IFNULL(DESIGN,”BENCHED”) FROM EMPLOYEE;

Note: The value being substituted for NULL values through IFNULL() should be of the same data type as that of the column.

51 of 114

SQL CONSTRAINTS

Constraint is a condition or check applicable on a field or set of fields.

  1. NOT NULL

If you do not want to allow NULL value in a column, you will want to place a NOT NULL constraint.

CREATE TABLE Customer

( CID int PRIMARY KEY,

NAME char(10) NOT NULL,

Amount float NOT NULL,

Discount float );

52 of 114

SQL CONSTRAINTS

  1. DEFAULT

The DEFAULT constraint provides default value to a

column when the INSERT INTO statement does not provide a specific value

CREATE TABLE Customer

( CID int PRIMARY KEY,

NAME char(10) NOT NULL,

Amount float NOT NULL,

Discount float DEFAULT 0.0);

53 of 114

SQL CONSTRAINTS

INSERT INTO CUSTOMER(CID,NAME, Amount)

VALUES (1,”Amy”,1234)

54 of 114

SQL CONSTRAINTS

3. UNIQUE:

The UNIQUE constraint ensures that all the values in a column are distinct.

CREATE TABLE Customer

( CID int PRIMARY KEY,

NAME char(10) ,

Phone int UNIQUE,

Amount float NOT NULL,

CITY CHAR(10) DEFAULT ‘DELHI’,

Discount FLOAT DEFAULT 0.0);

55 of 114

SQL CONSTRAINTS

4. CHECK:

The CHECK constraint ensures that all the values in a column satisfy certain conditions

CREATE TABLE Customer

( CID int PRIMARY KEY ,

NAME char(10) NOT NULL ,

Phone int UNIQUE ,

Amount float CHECK(Amount > 100),

COMPANY VARCHAR(10) DEFAULT ‘BGSNPS’);

56 of 114

SQL CONSTRAINTS

5. PRIMARY KEY:

Used to uniquely identify each row in a table

CREATE TABLE Customer

( CID int PRIMARY KEY ,

NAME char(10) ,

Phone int UNIQUE,

Amount float CHECK(Amount > 100) );

57 of 114

SQL CONSTRAINTS

5. PRIMARY KEY:

Used to uniquely identify each row in a table

CREATE TABLE Customer

( CID int,

NAME char(10) ,

Phone int UNIQUE,

Amount float,

PRIMARY KEY (CID) );

58 of 114

SQL CONSTRAINTS

5. PRIMARY KEY:

Used to uniquely identify each row in a table

CREATE TABLE Customer

( CID int,

NAME char(10) ,

Phone int UNIQUE,

Amount float,

PRIMARY KEY (CID,NAME) );

59 of 114

6. FOREIGN KEY:

When 2 tables are related by a common column , then the related column of the parent table should be declared as the primary or Unique field and the related column in child table should have the FOREIGN Key constraint

60 of 114

COLUMN NAME

CHARACTERISTICS

CID

Primary key

Name

Amount

TABLE : CUSTOMER

TABLE : ORDER

COLUMN NAME

CHARACTERISTICS

OID

Primary key

CID

Foreign key

DATE

FOOD

CREATE TABLE ORDER1

(OID int Primary key,

CID INT,

DATE date,

FOOD char(10),

FOREIGN KEY (CID) REFERENCES CUSTOMER(CID));

61 of 114

What does the following statement mean?

CREATE TABLE Item

( Icode char(5) NOT NULL,

Desc char(5) NOT NULL,

ROL int,

QOH int,

CHECK( ROL < QOH ),

UNIQUE (Icode, Desc) );

62 of 114

MYSQL FUNCTIONS

  • String Functions used The string string functions functions of are MySQL being can discussed manipulate below.the text string in many ways. Some commonly

63 of 114

64 of 114

65 of 114

GROUP BY

  • The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country".
  • The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or more columns.

  • Select count(*) from Customer

GROUP BY Country;

66 of 114

GROUP BY

  • It is used in SELECT statement to divide the table into groups. Grouping can be done column wise.

eg

SELECT COMPANY, count(*) FROM SONY

GROUP BY Company;

SELECT Company, max(Price),Min(Price) FROM SONY

GROUP BY Company;

Sno

Item

Qty

Price

Company

Supcode

City

1

Pen Drive

70

300

Dell

S109

Delhi

2

Camera

50

4500

Lenovo

S102

Delhi

3

Laptop

100

35000

Lenovo

S112

Delhi

4

Car GPS

30

12000

Dell

S103

Delhi

67 of 114

HAVING

  • This is used for placing conditions on groups in contrast to WHERE clause which places the condition on individual rows

  • Query to display the average marks from student table belonging to E grade.

SELECT AVG(marks) FROM STUDENT

GROUP BY Grade

HAVING GRADE=‘E’;

68 of 114

  • To display the jobs from the employee table where the number of employees is less than 3

SELECT JOB,COUNT(*) as EMPLOYEE

FROM EMPLOYEE

GROUP BY JOB

HAVING COUNT(*) < 3;

EMPLOYEE

JOB

5

DOCTOR

2

ENGINEER

4

CA

1

ARCHITECT

7

TEACHER

69 of 114

  • To display the jobs from the employee table where the number of employees is less than 3

SELECT JOB,COUNT(*) FROM EMPLOYEE

GROUP BY JOB

HAVING COUNT(*) < 3;

EMPLOYEE

JOB

5

DOCTOR

2

ENGINEER

4

CA

1

ARCHITECT

7

TEACHER

70 of 114

  • To display the Item and double the original Price

SELECT Item, 2*Price FROM SONY;

Sno

Item

Qty

Price

Company

Supcode

City

1

Pen Drive

70

300

Dell

S109

Delhi

2

Camera

50

4500

Lenovo

S102

Delhi

3

Laptop

100

35000

Lenovo

S112

Delhi

4

Car GPS

30

12000

Dell

S103

Delhi

71 of 114

DELETE

  • Delete commands removes rows from a table, this removes the entire row

  • Delete the row from the table SONY where ID is 121

DELETE FROM SONY

WHERE Id=121;

To remove all the items from the table

DELETE FROM SONY;

To delete the table

DROP TABLE SONY;

72 of 114

REVISE

  • CREATE
  • INSERT
  • SELECT
  • WHERE
  • IN // AND //OR //NOT //BETWEEN
  • ORDER BY
  • COUNT
  • GROUP BY
  • HAVING
  • DELETE

73 of 114

UPDATE TABLE

  • Sometimes you need to change the values of the existing table,this is made possible using update command.

syntax

UPDATE <TABLE NAME>

SET <COL NAME>= VALUE;

For eg change all the price from table sony to 2000

UPDATE SONY

SET Price=2000;

74 of 114

  • double the price from sony table where qty is more than 30

update sony

set Price=Price*2

where qty>30;

  • Assign Price as 5000 and qty as 100 from table sony where the company is from Dell

update sony

set Price=5000,Qty=100

where Company=‘Dell’;

75 of 114

  • To modify an existing column ie to increase the size

syntax is

ALTER TABLE <table name>

MODIFY (<COL> new data type(new size));

eg

ALTER TABLE EMP

MODIFY (Job char(30));

76 of 114

ALTER TABLE

  • It is used to add or delete or modify a column in a relation
  • The syntax to add a column is

ALTER TABLE <table name>

ADD <COL><DATATYPE><SIZE>;

ALTER TABLE <table name>

DROP <COL>; //Deleted column

  • The new column will be added with NULL values for all rows currently in the table.

EG

ALTER TABLE SONY

ADD Discount int(3);

77 of 114

  • ALTER – DROP
  • ALTER – RENAME
  • ALTER ADD PRIMARY KEY

78 of 114

DATE DATA TYPE

  • If you want the current date the query is

select curdate();

79 of 114

USING DATE DATA TYPE

CREATE TABLE Trial

( sno int PRIMARY KEY,

DOB date);

INSERT INTO Trial VALUES

(1,’2000-12-1’),

(2,’2004-3-2’);

80 of 114

`

  • If you want it to display in any other format ( not save in the table)

SELECT name, Date_format(DOB,’%d-%b-%y’) AS DOB from Trial;

81 of 114

82 of 114

83 of 114

  • Query to select all the details from the table trial where the DOB is before 1-1-2000

  • SELECT * FROM TRIAL
  • WHERE DOB < ‘1-1-2000’;

  • Query to select all the details from the table trial where the DOB is between 1-1-2000 and 1-1-2005

84 of 114

DATA DEFINITION LANGUAGE

  • A database is specified by a set of definition which are expressed by a special language called the data definition language (DDL)
  • The DDL provides a set of definition to specify the storage structure and access the methods used by the database system.
  • create, alter, drop

85 of 114

DATA MANIPULATION LANGUAGE

  • After the database has been created the data can be manipulated using a set of procedures which are expressed by a special language called data manipulation Language.
  • like retrieval of data
  • insertion of data
  • deletion
  • modification

  • INSERT , SELECT , UPDATE, DELETE

86 of 114

TCL

  • Transaction Control Language(TCL) commands are used to manage transactions in the database. These are used to manage the changes made to the data in a table by DML statements.
  • Eg COMMIT – Commit command is used to permanently save any transaction into the database.

  • ROLLBACK – This command restores the database to the last committed state.

  • SAVEPOINT – It is a point in a transaction when you can roll the transaction back to a certain point without rolling back the entire transaction.

87 of 114

THE RELATIONAL ALGEBRA

The relational algebra include

  • select
  • project
  • cartesian product
  • union
  • join

  • select, projection will work with one relation
  • All the other are binary operations

88 of 114

SELECT OPERATION

  • σ
  • work with horizontal subset
  • eg

select * from student

where roll<12

89 of 114

PROJECT OPERATION

  • ϖ
  • work with horizontal subset

eg:

select name from student;

90 of 114

THERE CAN BE MANY TYPES OF JOIN

  • CARTESIAN PRODUCT : An SQL join query without any join condition will return all the records of joined with all the records of the other table. It is also known as CROSS JOIN

  • EQUI JOIN : An SQL join query that joins two or more tables based on a condition using equality operator.

or

  • NATURAL JOIN: It is type of equi join where the join condition compares all the same name columns in both the tables

91 of 114

92 of 114

93 of 114

CARTESIAN PRODUCT �

  • x
  • A x B

94 of 114

CARTESIAN PRODUCT

95 of 114

96 of 114

SELECT * FROM T,S;

97 of 114

EQUI- JOIN

  • SELECT * FROM T,S
  • WHERE T.TNO=S.TNO;

98 of 114

NATURAL JOIN

  • Natural Join joins two tables based on same attribute name and datatypes. The resulting table will contain all the attributes of both the table but keep only one copy of each common column.

  • SELECT * FROM T NATURAL JOIN S;

99 of 114

UNION-MULTIPLE QUERIES CAN BE COMBINED TO ONE AS�

  • SELECT * FROM T
  • UNION
  • SELECT * FROM S;
  • ( PROVIDED BOTH THE TABLES HAS THE SAME NUMBER OF COLUMNS AND HEADING)

100 of 114

101 of 114

  1. To display the details of those consumers whose address is Delhi.

Ans: Select ConsumerName from Consumer

where Address = “Delhi”;

2. To display the details of stationary whose Price is in the range of  8 to 15(Both value included).

select * from stationary 

where price between 8 AND 15;

102 of 114

4.To display the ConsumerName and StationaryName in ascending order of ConsumerName

select ConsumerName, Stationary Name

From Stationary S, Consumer C

where S.S_ID=C.S_ID

ORDER BY ConsumerName;

103 of 114

5. To display the ConsumerName,Address from Table Consumer and Company and Price from table Stationary

SELECT ConsumerName, Address,Company, Price from Stationary, Consumer

where Stationary.S_ID=Consumer.S_ID;�

104 of 114

  1. To increase the Price of all stationary by 2
  2. To display the number of records of each company.
  3. To display the stationary name and address where SID of consumer is DP01
  4. To display all the details from consumer table whose consumer name starts with W
  5. To count the number of Consumer whose address is Delhi

105 of 114

DRAW THE OUTPUT OF THE SQL QUERIES

  1. SELECT DISTINCT Address FROM Consumer;
  2. SELECT Company,MAX(Price),MIN(Price),COUNT(*) FROM Stationary GROUP BY Company;
  3. SELECT Consumer.ConsumerName,

Stationary.StationaryName,

Stationary.Price from Stationary,Consumer

WHERE Consumer.S_ID=Stationary.S_ID;

4. SELECT StationaryName, Price*3 FROM Stationary;

106 of 114

VIEW

  • A view is like a window through which you can view or change information in a table.
  • A view is a virtual table
  • it looks like a table but does not exist.
  • its derived from the base table

107 of 114

CREATE VIEW

  • View is a virtual table that we get after each query.
  • The SQL provides a stmt for creating view called the CREATE VIEW
  • Eg
  • CREATE VIEW tax

AS SELECT *

FROM employee

WHERE GROSS >8000;

Now this view will be having all the details of the employees that have gross more than 8000.

Now this view can be used just like any other table.

SELECT * FROM tax;

108 of 114

  • The SELECT statement used in the view definition cannot include :
  • order by clause
  • INTO clause

  • DROP VIEW COMMAND

DROP VIEW tax

109 of 114

DUAL TABLE

  • Oracle database has introduced a dummy table called dual.
  • DUAL table is a small worktable which has one row and one column
  • It can be used to obtain calculation and also system date.
  • eg
  • SELECT 5*6 FROM DUAL;

110 of 114

111 of 114

SOME BUILT IN FUNCTIONS

FUNCTION

COMMAND

OUTPUT

LOWER

SELECT LOWER(“HELLO”)

FROM DUAL;

hello

UPPER

SELECT UPPER(“hello”)

FROM DUAL;

HELLO

REPLICATE

SELECT REPLICATE(“&*”,4)

FROM DUAL;

&*&*&*&*

SUBSTR

SELECT SUBSTR(“COMPUTER”,4,3)

FROM DUAL;

PUT

GETDATE(),

SYSDATE()

112 of 114

QUESTIONS�

  1. Write two examples of DBMS software?
  2. What is meant by NULL value in MySQL?
  3. Table “Club” has 4 rows and 3 columns. Table “Manager” has 2 rows and 5 columns, What will be the cardinality and degree of the cartesian product of them?
  4. Name two datatypes for storing alphanumeric value.
  5. Define a Query
  6. What is the use of UPDATE statement? How is it different from ALTER statement.
  7. Which command is used to delete the following from the database?

a) relation b) tuple c) Attribute

113 of 114

114 of 114

QUESTIONS BASED ON THE TABLE

  1. SQL statement to find the highest price from the table Book_information
  2. SQL statement to find the sales amount for each store from sales table
  3. List all the stores whose total sales amount is over 500
  4. SQL statement to find the total sales amount for store ID 25 and total sales amount for store ID 45.
  5. To find the average exam score for EXAM_ID =1
  6. To find out how many students took each exam?
  7. To print the record of all the students whose last name starts with ‘L’.