Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 127

DF\

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 1


Chapter 4
Structured Query Language
(SQL)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe


Structured Query Language (SQL)
 SQL is a standard Database language that is used
to create, maintain, and retrieve the relational
database.
 The steps required to execute SQL statement are
handled transparently by the SQL database.
 SQL is used for the following:
 Adding, updating and deleting rows of data.
 Modifying database table and index structures.
 Retrieving subsets of information from relational
database management systems (RDBMS)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 3


Characteristics of SQL
 SQL is easy to learn.
 SQL is an ANSI and ISO standard computer
language for creating and manipulating database.
 It allows the user to create Create , Update,
Delete and Retrieve data from a database.
 SQL can execute queries against the database.
 SQL is used to describe the data.
 SQL allows users to set permissions on tables,
procedures, and views.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 4


Advantages
 Fast Data Sharing - Database administration makes it possible for
consumers to access more and better-managed data. DBMS enables
end users to quickly scan their environment and react to any
alterations made there.
 Portable - SQL can be run on any platform even it can be executed on
PCs , Laptops , Servers and Mobile.
 No Coding Required - Using standard SQL it is easier to manage
database systems without writing large amount of code.
 Secured Data - The likelihood of security problems increases as a
database becomes more functional and accessible.
 Reduces Data Inconsistency and Redundancy - The major issues
faced during the process of storing data are inconsistency and
redundancy. Inconsistent data may lead to a big loss to an individual
or a business model

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 5


Data Types in SQL

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 6


Data Types
Data Type Use

CHAR It has fixed sized. Stores data of fixed length

VARCHAR It accepts character and string type of data . It has


variable size

INT Integer used to accept numeric values.

FLOAT Accept approximate numeric values

DATE Accept Date type of values

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 7


Additional Data Types in SQL
Has DATE, TIME, and TIMESTAMP data types
 DATE:

 Made up of year-month-day in the format yyyy-mm-dd


 TIME:
 Made up of hour:minute:second in the format hh:mm:ss
 TIME(i):
 Made up of hour:minute:second plus i additional digits
specifying fractions of a second
 format is hh:mm:ss:ii...i

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 8


Types of SQL
 SQL commands are instructions. It is used to communicate
with the database. It is also used to perform specific tasks,
functions, and queries of data.
 SQL can perform various tasks like create a table, add data
to tables, drop the table, modify the table, set permission for
users.
1. Data Definition Language (DDL)
2. Data Manipulation Language (DML)
3. Data Control Language (DCL)
4. Data Query Language (DQL)
5. Transaction Control Language (TCL)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 9


Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 10
Data Definition Language(DDL)
 DDL (Data Definition Language) is a type of SQL
command used to define data structures and
modify data.
 It creates, alters, and deletes database objects
such as tables, views, indexes, and users.
Examples of DDL statements include CREATE,
ALTER, DROP

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 11


CREATE TABLE
 CREATE: It is used to create objects in the
database, such as tables, views, stored
procedures, and more.
CREATE DATABASE COLLEGE;

CREATE TABLE STUDENT (


ROLL_No INTEGER
SNAME VARCHAR(10) NOT
NULL,
NUMBER INTEGER NOT
NULL,
ADDRESS CHAR(20),
DOB DATE );

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 12


ALTER TABLE

 Used to add an attribute to one of the base relations


 The new attribute will have NULLs in all the tuples of the
relation right after the command is executed; hence, the
NOT NULL constraint is not allowed for such an
attribute
 Example:
ALTER TABLE EMPLOYEE ADD EMAIL
VARCHAR(12);

 The database users must still enter a value for the


new attribute JOB for each EMPLOYEE tuple.
 This can be done using the UPDATE command.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 13


TRUNCATE
 The Truncate statement is a DDL or Data
Definition Language command that is used to
delete the complete data from the table without
deleting the table structure.
 Example:
TRUNCATE TABLE TABLE_NAME;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 14


DROP TABLE
 Used to remove a relation (base table) and its
definition
 The relation can no longer be used in queries,
updates, or any other commands since its
description no longer exists
 Example:

DROP TABLE STUDENT;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 15


Retrieval Queries in SQL (contd.)
 A bag or multi-set is like a set, but an element
may appear more than once.
 Example: {A, B, C, A} is a bag. {A, B, C} is also a
bag that also is a set.
 Bags also resemble lists, but the order is irrelevant
in a bag.
 Example:
 {A, B, A} = {B, A, A} as bags
 However, [A, B, A] is not equal to [B, A, A] as lists

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 16


Retrieval Queries in SQL (contd.)
 Basic form of the SQL SELECT statement is called a
mapping or a SELECT-FROM-WHERE block

SELECT <attribute list>


FROM <table list>
WHERE <condition>

 <attribute list> is a list of attribute names whose values are


to be retrieved by the query
 <table list> is a list of the relation names required to process
the query
 <condition> is a conditional (Boolean) expression that
identifies the tuples to be retrieved by the query

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 17


Simple SQL Queries (contd.)
 Example of a simple query on one relation

 Query 0: Retrieve the birthdate and address of


the employee whose name is 'John B. Smith'.
: SELECT BDATE, ADDRESS
FROM EMPLOYEE
WHERE FNAME='John' AND MINIT='B’
AND LNAME='Smith’
 Similar to a SELECT-PROJECT pair of relational algebra
operations:
 The SELECT-clause specifies the projection attributes and the
WHERE-clause specifies the selection condition
 However, the result of the query may contain duplicate
tuples

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 18


Simple SQL Queries (contd.)
 Query 1: Retrieve the name and address of all employees
who work for the 'Research' department.

Q1: SELECT FNAME, LNAME, ADDRESS


FROM EMPLOYEE, DEPARTMENT
WHERE DNAME='Research' AND
DNUMBER=DNO

 Similar to a SELECT-PROJECT-JOIN sequence of


relational algebra operations
 (DNAME='Research') is a selection condition (corresponds
to a SELECT operation in relational algebra)
 (DNUMBER=DNO) is a join condition (corresponds to a
JOIN operation in relational algebra)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 19


Simple SQL Queries (contd.)
 Query 2: For every project located in 'Stafford', list the project
number, the controlling department number, and the department
manager's last name, address, and birthdate.

Q2: SELECT PNUMBER, DNUM, LNAME, BDATE, ADDRESS


FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE DNUM=DNUMBER AND MGRSSN=SSN
AND PLOCATION='Stafford'

 In Q2, there are two join conditions


 The join condition DNUM=DNUMBER relates a project to its
controlling department
 The join condition MGRSSN=SSN relates the controlling
department to the employee who manages that department

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 20


Set Operations in SQL

 Set operators combine the results of two component


queries into a single result. Queries containing set
operators are called compound queries.

Operator Returns

UNION All distinct rows selected by either query

UNION ALL All rows selected by either query, including all duplicates

INTERSECT All distinct rows selected by both queries

MINUS All distinct rows selected by the first query but not the second

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 21


UNION Operation

UNION is used to combine the results of two or


more SELECT statements. However it will eliminate
duplicate rows from its result set. In case of union, number
of columns and datatype must be same in both the tables,
on which UNION operation is being applied.

Syntax
SELECT * FROM table_name1
UNION
SELECT * FROM table_name2;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 22


Example SELECT * FROM First
UNION
First table SELECT * FROM Second;
ID Name
1 abhi Result set table
2 adam
ID NAME
Second table 1 abhi
ID Name 2 adam
2 adam 3 Chester
3 Chester

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 23


Example2 SELECT Name FROM First
UNION
First table SELECT Name FROM Second;
ID Name
1 abhi Result set table
2 adam
NAME
Second table abhi
ID Name adam
2 adam Chester
3 Chester

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 24


Union All Operation
 Union All operation is equal to the Union
operation. It returns the set without removing
duplication and sorting the data.
Syntax:

SELECT * FROM table1


UNION ALL
SELECT * FROM table2;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 25


Example SELECT * FROM First
UNION ALL
First table SELECT * FROM Second;
ID Name
1 abhi Result set table
2 adam
ID NAME
Second table 1 abhi
2 adam
ID Name
2 adam
2 adam
3 Chester
3 Chester

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 26


Example2 SELECT Name FROM First
UNION ALL
First table SELECT Name FROM Second;
ID Name
1 abhi Result set table
2 adam
NAME
Second table abhi
adam
ID Name
adam
2 adam
Chester
3 Chester

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 27


Intersect operation
 Intersect operation is used to combine
two SELECT statements, but it only retuns the records
which are common from both SELECT statements.
 In case of Intersect the number of columns and datatype

must be same.
Syntax:
SELECT * FROM table1
INTERSECT
SELECT * FROM table2;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 28


Example SELECT * FROM First
INTERSECT
First table SELECT * FROM Second;
ID Name
1 abhi Result set table
2 adam

Second table ID NAME


ID Name 2 adam
2 adam
3 Chester

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 29


Minus Operation
 It combines the result of two SELECT statements.
Minus operator is used to display the rows which are
present in the first query but absent in the second
query.
 It has no duplicates and data arranged in ascending

order by default.
Syntax:
SELECT * FROM table1
MINUS
SELECT * FROM table2;
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 30
Example SELECT * FROM First
MINUS
First table SELECT * FROM Second;
ID Name
1 abhi Result set table
2 adam

Second table ID NAME


ID Name 1 abhi
2 adam
3 Chester

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 31


Aggregate Functions

 An aggregate function in SQL performs a


calculation on multiple values and returns a
single value.
 SQL provides many aggregate functions that
include avg, count, sum, min, max, etc.
 An aggregate function ignores NULL values when
it performs the calculation, except for the count
function.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 32


Functions Name
 Total : sum
 Minimum : min
 Maximum : max
 Count : count
 Average : avg

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 33


Total : sum

 Sum function is used to calculate the sum of all


selected columns.
 It works on numeric fields only.
 Syntax
SUM( [ALL|DISTINCT] expression )

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 34


Example
PRODUCT_MAST Table Name

PRODUCT COMPANY QTY RATE COST

Item1 Com1 2 10 20

Item2 Com2 3 25 75

Item3 Com1 2 30 60

Item4 Com3 5 10 50

Item5 Com2 2 20 40

Item6 Cpm1 3 25 75

Item7 Com1 5 30 150

Item8 Com1 3 10 30

Item9 Com2 2 25 50

Item10 Com3 4 30 120

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 35


Query : Display total Cost from table
Product_mast using aggregate
function
Soln: SELECT SUM(COST)
FROM PRODUCT_MAST;
Output: 670
Query: Display total Cost from table Product_mast using
aggregate function whose Quantity should be more than 3
SELECT SUM(COST)
FROM PRODUCT_MAST
WHERE QTY>3;
Output: 320

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 36


Minimum : Min
 MIN function is used to find the minimum value of
a certain column. This function determines the
smallest value of all selected values of a column.
 Syntax:
MIN()
or
MIN( [ALL|DISTINCT] expression )

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 37


Query : Display minimum Rate from
table Product_mast using aggregate
function

 Soln: SELECT MIN(RATE)


FROM PRODUCT_MAST;

Output: 10

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 38


Maximum : Max
 MAX function is used to find the maximum value
of a certain column. This function determines the
largest value of all selected values of a column.
 Syntax:
MAX()
or
MAX( [ALL|DISTINCT] expression )

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 39


Query : Display maximum Rate from
table Product_mast using aggregate
function

 Soln: SELECT MAX(RATE)


FROM PRODUCT_MAST;

Output: 25

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 40


Average: AVG
 The AVG function is used to calculate the
average value of the numeric type.
 AVG function returns the average of all non-Null
values.

 Syntax:
AVG()
or
AVG( [ALL|DISTINCT] expression )

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 41


Query : Display average Rate from
table Product_mast using aggregate
function

 Soln: SELECT AVG(COST)


FROM PRODUCT_MAST;

Output: 67.00

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 42


Count: count
 COUNT function is used to Count the number of
rows in a database table. It can work on both
numeric and non-numeric data types.
 COUNT function uses the COUNT() that returns the
count of all the rows in a specified table. COUNT()
considers duplicate and Null.
 Syntax
COUNT()
or
COUNT( [ALL|DISTINCT] expression )
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 43
Query : Display count from table
Product_mast using aggregate
function

 Soln: SELECT COUNT(*)


FROM PRODUCT_MAST;

Output: 10

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 44


Data Manipulation Language (DML)

Data Manipulation Language (DML) is a class of SQL


statements that are used to query, edit, add and
delete row-level data from database tables or views.
The main DML statements are INSERT, DELETE,
and UPDATE.
Following are the four main DML commands in

SQL:
INSERT Command

UPDATE Command

DELETE Command

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 45


INSERT DML Command

 INSERT is another most important data manipulation


command in Structured Query Language, which allows
users to insert data in database tables.
 Syntax:
INSERT INTO TABLE_NAME VALUES
(column_Name1, column_Name 2 …..column_Name N )

Example:
INSERT INTO Student VALUES (104, ’Anmol’, 89, 19)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 46


 Example 1: This example describes how to insert
the record in the database table.
 Let's take the following student table, which consists
of only 2 records of the student.
Stu_Id Stu_Name Stu_Marks Stu_Age

101 Ramesh 92 20
201 Jatin 83 19

Suppose, you want to insert a new record into the student table.
For this, you have to write the following DML INSERT
command:

INSERT INTO Student (Stu_id, Stu_Name, Stu_Marks, Stu_Age)


VALUES (104, ’Anmol’, 89, 19)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 47


UPDATE DML Command

 The UPDATE statement in SQL is used to update the


data of an existing table in the database.
 We can update single columns as well as multiple

columns using the UPDATE statement as per our


requirement.
 Syntax :

UPDATE table_name SET column_name


=new_value[WHERE condition]

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 48


Example:Change username from student table
where student Id is 3
Student

Student_Id FirstName LastName User_Name

1 Ada Sharma sharmili


2 Rahul Maurya sofamous
3 James Walker jonny

UPDATE Student
SET User_Name = 'beinghuman'
WHERE Student_Id = '3'
Student_Id FirstName LastName User_Name

1 Ada Sharma sharmili


2 Rahul Maurya sofamous
3 James Walker beinghuman

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 49


Updating Multiple Fields:
 If you are going to update multiple fields, you should separate
each field assignment with a comma.
 SQL UPDATE statement for multiple fields:
UPDATE student
SET User_Name = 'beserious', First_Name = 'Johnny'
WHERE Student_Id = '3'

Student_Id FirstName LastName User_Name

1 Ada Sharma sharmili


2 Rahul Maurya sofamous
3 Johnny Walker beserious

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 50


DELETE DML Command

 The SQL DELETE statement is used to delete


rows from a table. Generally DELETE statement
removes one or more records from a table.
 Syntax:
DELETE from table_name;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 51


 SQL DELETE Syntax
 Let's see the Syntax for the SQL DELETE
statement:

DELETE FROM table_name [WHERE condition];

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 52


DELETE FROM EMPLOYEE WHERE ID=101;
ID EMP_NAME CITY SALARY

102 Sanjay Singh Meerut 21000

103 Priyanka Sharma Raipur 25000

104 Esha Singhal Delhi 26000

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 53


Data Control Language (DCL)

 DCL commands are used for controlling the user


access in a database.
 DCL commands are used to grant and take back
authority from any database user.
 Here are some commands that come under DCL:
 Grant – Users gets Access privileges to database.
 Revoke - It is used to take back permissions from
the user.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 54


 GRANT Syntax:-

GRANT SELECT , INSERT , UPDATE , DELETE ON


tablename TO username;
 Example:

 GRANT SELECT ON student TO Jay;


 GRANT SELECT , UPDATE , DELETE ON student
TO Jay;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 55


REVOKE Syntax:-
REVOKE SELECT , INSERT , UPDATE , DELETE ON
tablename FROM username;

EXAMPLE :-

REVOKE SELECT ON student FROM John;


REVOKE UPDATE, DELETE ON student FROM Smith;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 56


Data Query Language (DQL)
 DQL is used to fetch the data from the database.
 It uses only one command:
 SELECT
 This is the same as the projection operation of
relational algebra. It is used to select the attribute
based on the condition described by WHERE clause.
SELECT expressions
FROM TABLES
WHERE conditions;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 57


SELECT

 SELECT is the most important data manipulation


command in Structured Query Language.
 The SELECT command shows the records of the

specified table. Without using WHERE Clause.


 Syntax:

SELECT column_Name FROM Name_of_table;


Here, column_Name_1, column_Name_2, …..,
column_Name_N are the names of those columns whose
data we want to retrieve from the table.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 58


 Example 1: This example shows all the values of
every column from the table.

SELECT * FROM Student;


‘*’ It represents all the columns .
This SQL statement displays the following values of the
student table:
Student_ID Student_Name Student_Marks
BCA1001 Abhay 85
BCA1002 Anuj 75
BCA1003 Bheem 60
BCA1004 Ram 79
BCA1005 Sumit 80

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 59


 Example 2: This example shows all the values of
a specific column from the table.

SELECT Emp_Id, Emp_Salary FROM Employee;

 This SELECT statement displays all the values


of Emp_Salary and Emp_Id column of Employee table:
Emp_Id Emp_Salary
201 25000
202 45000
203 30000
204 29000
205 40000

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 60


 Example 3: This example describes how to use
the WHERE clause with the SELECT DML
command.

SELECT * FROM Student WHERE Stu_Marks = 80;

Student_ID Student_Name Student_Marks


BCA1001 Abhay 80
BCA1003 Bheem 80
BCA1005 Sumit 80

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 61


DISTINCT Clause
 This clause is used to avoid selection of Duplicate
Rows.
 Syntax

SELECT DISTINCT(column_name) FROM


table_name;

Example:
SELECT DISTINCT(Job) FROM Employee;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 62


CREATE SCHEMA
 Specifies a new database schema by giving it a
name

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 63


SET OPERATIONS
 SQL has directly incorporated some set operations
 There is a union operation (UNION), and in some versions
of SQL there are set difference (MINUS) and intersection
(INTERSECT) operations
 The resulting relations of these set operations are sets of
tuples; duplicate tuples are eliminated from the result
 The set operations apply only to union compatible
relations; the two relations must have the same attributes
and the attributes must appear in the same order

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 64


UNION in sql
 The SQL Union operation is used to combine the result of
two or more SQL SELECT queries.
 In the union operation, all the number of datatype and
columns must be same in both the tables on which UNION
operation is being applied.
 The union operation eliminates the duplicate rows from its
resultset.
 Syntax
SELECT column_name FROM table1
UNION
SELECT column_name FROM table2;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 65


First table Second table
ID NAME
ID NAME
1 Jack
3 Jackson
2 Harry 4 Stephan
3 Jackson 5 David

Union SQL query will be:


SELECT * FROM First
UNION
SELECT * FROM Second;
ID NAME

1 Jack
2 Harry
3 Jackson
4 Stephan
5 David
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 66
UNION ALL

 Union All operation is equal to the Union


operation.
 It returns the set without removing duplication

and sorting the data.


 Syntax:

SELECT column_name FROM table1


UNION ALL
SELECT column_name FROM table2;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 67


 Union All query will be like:
SELECT * FROM First
UNION ALL
SELECT * FROM Second;
ID NAME

1 Jack
2 Harry
3 Jackson
3 Jackson
4 Stephan
5 David

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 68


INTERSECT
 It is used to combine two SELECT statements.
The Intersect operation returns the common rows
from both the SELECT statements.
 In the Intersect operation, the number of datatype
and columns must be the same.
 It has no duplicates and it arranges the data in
ascending order by default.
 Syntax
SELECT column_name FROM table1
INTERSECT
SELECT column_name FROM table2;
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 69
 Intersect query will be:
SELECT * FROM First
INTERSECT
SELECT * FROM Second;

ID NAME

3 Jackson

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 70


MINUS
 It combines the result of two SELECT statements.
Minus operator is used to display the rows which
are present in the first query but absent in the
second query.
 It has no duplicates and data arranged in
ascending order by default.
 Syntax:
SELECT column_name FROM table1
MINUS
SELECT column_name FROM table2;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 71


 Minus query will be:

SELECT * FROM First


MINUS
SELECT * FROM Second;
ID NAME

1 Jack
2 Harry

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 72


STRING Operation

 SQL specifies strings by enclosing them in single


quotes, e.g ‘STRING’.
 Commonly used operation on string is pattern
matching using the operator LIKE.
 String describe patterns by using two special
characters.
1. Percent(%): Character matches any Substring.
2. Underscore(_): Matches any character.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 73


 Here patterns are Case Sensitive where Upper case
Characters do not match Lower case character or
vice-versa.
 Example:
1. ‘%Engineering’ – It will matches any string containing
“Engineering” as substring e.g ‘Computer
Engineering’ or ‘Civil Engineering’.
2. ‘Department of%’ - It will matches any string
containing ‘Department of’ as first string e.g
‘Department of Computer’ , ‘Department of College’.
3. ‘_ _ _’ – Matches any string with exactly three
charactes.
4. ‘_s%’ – Matches any string with second character ‘s’.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 74


 Example:
Q Find the names of author from the table where first
two characters of name are ‘Ba’.
SQL> SELECT Author_name
FROM Author
WHERE Authotr_name LIKE ‘Ba%’;.
Q Display the names of all publishers whose address
includes the substring ‘%Vashi%’.
SQL> SELECT Publisher_name
FROM Publisher
WHERE Address LIKE ‘%Vashi%’;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 75


AGGREGATE FUNCTIONS
 Include COUNT, SUM, MAX, MIN, and AVG
 Query: Find the maximum salary, the minimum
salary, and the average salary among all
employees.
Q: SELECT MAX(SALARY),
MIN(SALARY),
AVG(SALARY)
FROM EMPLOYEE

 Some SQL implementations may not allow more


than one function in the SELECT-clause

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 76


AGGREGATE FUNCTIONS (contd.)
 Queries : Retrieve the total number of employees
in the company and the number of employees in
the 'Research' department .
Q : SELECT COUNT (*)
FROM EMPLOYEE

Q: SELECT COUNT (*)


FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND
DNAME='Research’

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 77


AGGREGATE FUNCTIONS (contd.)
 Query : Find the maximum salary, the minimum
salary, and the average salary among employees
who work for the 'Research' department.
Q : SELECT
MAX(SALARY),
MIN(SALARY), AVG(SALARY)
FROM EMPLOYEE,
DEPARTMENT
WHERE DNO=DNUMBER AND
DNAME='Research'

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 78


NULL Values
 A field with a NULL value is a field with no value.
 If a field in a table is optional, it is possible to
insert a new record or update a record without
adding a value to this field. Then, the field will be
saved with a NULL value.
 We will have to use the IS NULL and IS NOT
NULL operators .

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 79


 IS NULL Syntax:

SELECT column_names
FROM table_name
WHERE column_name IS NULL;

 IS NOT NULL Syntax:

SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 80


Example
PRODUCT_MAST Table Name

PRODUCT COMPANY QTY RATE COST

Item1 Com1 2 10 20

Item2 Com2 3 25 75

Item3 Com1 2 30 60

Item4 Com3 5 10 50

Item5 Com2 2 NULL NULL

Item6 Cpm1 3 25 75

Item7 Com1 5 30 NULL

Item8 Com1 3 10 30

Item9 Com2 2 25 50

Item10 Com3 4 30 120

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 81


Query: Find all Products from
PRODUCT_MAST with null values for
cost field
 Soln:
SELECT Product
FROM PRODUCT_MAST
WHERE Cost IS NULL;
Output: Product
Item5
Item7

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 82


Query: Find all Products from
PRODUCT_MAST where Cost is not null
 Soln:
SELECT Product Product

FROM PRODUCT_MAST Item1


Item2
WHERE Cost IS NOT NULL;
Item3
Output: Item4

Item6

Item8
Item9

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 83


GROUPING CLAUSE
 In many cases, we want to apply the aggregate
functions to subgroups of tuples in a relation
 Each subgroup of tuples consists of the set of
tuples that have the same value for the grouping
attribute(s)
 The function is applied to each subgroup
independently
 SQL has a GROUP BY-clause for specifying the
grouping attributes, which must also appear in
the SELECT-clause

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 84


GROUPING
 Query : For each department, retrieve the department
number(DNO), the number of employees in the
department, and their average salary.
Q: SELECT DNO, COUNT (*), AVG (SALARY)
FROM EMPLOYEE
GROUP BY DNO
 In Q, the EMPLOYEE tuples are divided into groups-
 Each group having the same value for the grouping attribute
DNO
 The COUNT and AVG functions are applied to each such
group of tuples separately
 The SELECT-clause includes only the grouping attribute
and the functions to be applied on each group of tuples
 A join condition can be used in conjunction with grouping

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 85


GROUPING
 Query : For each project, retrieve the project number,
project name, and the number of employees who work on
that project.

Q: SELECT PNUMBER, PNAME, COUNT


(*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER, PNAME

 In this case, the grouping and functions are applied after


the joining of the two relations

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 86


THE HAVING-CLAUSE
 It is used to overcome some of the limitation of the
WHERE clause.
 It is used with GROUP-BY and Aggregate functions.
 Sometimes we want to retrieve the values of these
functions for only those groups that satisfy certain
conditions
 The HAVING-clause is used for specifying a
selection condition on groups (rather than on
individual tuples)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 87


THE HAVING-CLAUSE (contd.)
 Query 22: For each project on which more than
two employees work, retrieve the project number,
project name, and the number of employees who
work on that project.
Q22: SELECT PNUMBER, PNAME,
COUNT(*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNUM
GROUP BY PNUMBER, PNAME
HAVING COUNT (*) > 2

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 88


JOIN IN SQL
 The join clause allows us to retrieve data from two or
more related tables into a meaningful result set.
 We can join the table using a SELECT statement and
a join condition. It indicates how SQL Server can use
data from one table to select rows from another table.
 In general, tables are related to each other
using foreign key constraints.
 The following are types of join supports in SQL Server:
 INNER JOIN
 OUTER JOIN

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 89


INNER JOIN
 This JOIN returns all records from multiple tables
that satisfy the specified join condition.
 It is the simple and most popular form of join and
assumes as a default join.
 If we omit the INNER keyword with the JOIN
query, we will get the same output.
 The following visual representation explains how INNER
JOIN returns the matching records from table1 and table2:

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 90


 INNER JOIN Syntax
 The following syntax illustrates the use of INNER
JOIN in SQL Server:

SELECT columns
FROM table1
INNER JOIN table2 ON condition

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 91


Employee Employee Salary
Emp_name City Emp_name Salary
Hari Pune Hari 10000
Om Mumbai Om 7000
Smith Nashik Bill 8000
Jay Solapur Jay 5000

SELECT Employee.Emp_name , Employee


Salary.Salary FROM Employee INNER JOIN
Employee Salary
ON Employee.Emp_name = Employee
Salary.Emp_name;
Emp_name Salary
Hari 10000
Om 7000
Jay 5000

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 92


OUTER JOIN

 Whenever the tables are joined using inner join ,


rows which contain matching value in the join
predicate are returned.
 But sometimes we want both the matching and
non-matching rows returned for the table that are
being joined. This is known as an Outer Join.
 Types
1. Left Join
2. Right Join
3. Full Join
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 93
LEFT OUTER JOIN

 This join returns matching rows from the table


being joined and non-matching rows from the left
table in the result and places Null values in the
attributes that comes from the Right table .
SELECT column_lists
FROM table1
LEFT [OUTER] JOIN table2
ON table1.column = table2.column;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 94


SELECT Employee.Emp_name , Salary FROM
Employee LEFT JOIN Employee Salary
ON Employee.Emp_name = Employee
Salary.Emp_name;

Emp_name Salary
Hari 10000
Om 7000
Jay 5000
Smith NULL

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 95


RIGHT OUTER JOIN

 This join returns matching rows from the table


being joined and non-matching rows from the Right
table in the result and places Null values in the
attributes that comes from the Left table .
SELECT column_lists
FROM table1
RIGHT [OUTER] JOIN table2
ON table1.column = table2.column;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 96


SELECT Employee.Emp_name , Salary FROM
Employee RIGHT JOIN Employee Salary
ON Employee.Emp_name = Employee
Salary.Emp_name;

Emp_name City Salary


Hari Pune 10000
Om Mumbai 7000

Jay Solapur 5000


Bill NULL 8000

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 97


FULL OUTER JOIN
This join returns matching data of both the tables
and the remaining rows of both left and right
table.
SELECT column_lists
FROM table1
FULL [OUTER] JOIN table2
ON table1.column = table2.column;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 98


SELECT Employee.Emp_name , Salary FROM
Employee FULL JOIN Employee Salary
ON Employee.Emp_name = Employee
Salary.Emp_name;

Emp_name City Salary

Hari Pune 10000

Om Mumbai 7000

Jay Solapur 5000

Smith Nashik NULL

Bill NULL 80000

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 99


VIEWS IN SQL

 Views in SQL are kind of virtual tables.


 It is a database object that has no values and its
contents are based on the base table or real table.
 It also has rows and columns as they are in a real
table in the database.
 We can create a view by selecting fields from one or
more tables present in the database.
 A View can either have all the rows of a table or
specific rows based on certain condition.
 In this article we will learn about creating , deleting
and updating Views.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 100
Sample Tables:
StudentDetails

Student Marks

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 101


CREATING VIEWS
 We can create View using CREATE VIEW statement. A
View can be created from a single table or multiple
tables.
 Syntax:
CREATE VIEW view_name AS
SELECT column1, column2..
FROM table_name
WHERE condition;
view_name: Name for the View
table_name: Name of the table
condition: Condition to select rows

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 102


Examples:
Creating View from a single table:
In this example we will create a View named

DetailsView from the table StudentDetails. Query:


CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM StudentDetails
WHERE S_ID < 5;
SELECT * FROM DetailsView;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 103


Creating View from multiple
tables:
 In this example we will create a View named
MarksView from two tables StudentDetails and
StudentMarks.
 To create a View from multiple tables we can simply
include multiple tables in the SELECT statement.
 Syntax:
CREATE VIEW View_name AS
SELECT view_name1.column1,
view_name1.column2, view_name2.column1
FROM view_name1, view_name2
WHERE condition;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 104


CREATE VIEW MarksView AS
SELECT StudentDetails.NAME,
StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME =
StudentMarks.NAME;

SELECT * FROM MarksView;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 105


NESTING OF QUERIES

 A nested query in SQL contains a query inside


another query.
 The outer query will use the result of the inner
query.
 For instance, a nested query can have
two SELECT statements, one on the inner query
and the other on the outer query.
 A complete SELECT query, called a nested query,
can be specified within the WHERE-clause of
another query, called the outer query
 Many of the previous queries can be specified in an
alternative form using nesting

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 106


Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 107
Syntax

SELECT column1, column2, ... FROM table1


WHERE column1 IN ( SELECT column1 FROM
table2 WHERE condition );

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 108


i) IN
 Set membership
 SQL uses IN and NOT IN constructs for set
membership tests.
i) IN
 IN is a connectivity tests for set membership, where the
set is a collection of values produced by a SELECT
clause.
 The IN operator checks if a column value in the outer
query's result is present in the inner query's result.
 The final result will have rows that satisfy
the IN condition.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 109


Employees
id name salary role
Augustine
1 10000 Developer
Hammond

2 Perice Mundford 10000 Manager

3 Cassy Delafoy 30000 Developer

4 Garwood Saffen 40000 Manager

5 Faydra Beaves 50000 Developer

Awards
id employee_id award_date
1 1 2022-04-01
2 3 2022-05-01

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 110


IN Example
Select all employees who won an
award.
SELECT id, name FROM Employees
WHERE id IN (SELECT employee_id FROM
Awards);

id name
1 Augustine Hammond
3 Cassy Delafoy

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 111


ii) NOT IN
 The NOT IN connective tests for the absence of
set membership.
 The NOT IN operator checks if a column value in
the outer query's result is not present in the
inner query's result. The final result will have rows
that satisfy the NOT IN condition.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 112


NOT IN Example
Select all employees who never won
an award.

SELECT id, name FROM Employees


WHERE id NOT IN (SELECT employee_id FROM
Awards);
id name
2 Perice Mundford
4 Garwood Saffen
5 Faydra Beaves

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 113


TRIGGER
 A trigger is called a special procedure because
it cannot be called directly like a stored
procedure.
 The key distinction between the trigger and
procedure is that a trigger is called automatically
when a data modification event occurs against a
table.
 A stored procedure, on the other hand, must be
invoked directly.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 114


Need of Trigger
 To generate data Automatically.
 Validate input data

 Replicate data to different files to achieve data consistency

Trigger Classification
 Classification based on Timing:

• BEFORE Trigger
• AFTER Trigger

 Classification based on Level:

• STATEMENT Level Trigger

• ROW Level Trigger

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 115


STATEMENT Level Trigger

 A statement-level trigger is executed once for the


entire triggering event, instead of once for each
row affected by the event.
 Statement-level triggers are useful to perform an
action based on the overall effect of an INSERT,
UPDATE or DELETE statement, rather than on
individual rows.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 116


ROW Level Trigger

 A row-level trigger is executed once for each row


affected by the triggering event, which is typically
an INSERT, UPDATE or DELETE statement.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 117


Syntax of Trigger

CREATE TRIGGER schema.trigger_name


ON table_name

AFTER {INSERT, UPDATE, DELETE}

[NOT FOR REPLICATION]

AS

{SQL_Statements}

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 118


Example

 Let us understand how we can work with triggers


in the SQL Server. We can do this by first
creating a table named 'Employee' using the
below statements:

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 119


 We will also create another table named
'Employee_Audit_Test' to automatically store
transaction records of each operation, such as
INSERT, UPDATE, or DELETE on the Employee
table:

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 120


CREATE TRIGGER trInsertEmployee
ON Employee
FOR INSERT
AS
BEGIN
Declare @Id int
SELECT @Id = Id from inserted
INSERT INTO Employee_Audit_Test
VALUES ('New employee with Id = ' + CAST(@Id AS VARCHAR(
10)) + ' is added at ' + CAST(Getdate() AS VARCHAR(22)))
END

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 121


CORRELATED NESTED QUERIES
 If a condition in the WHERE-clause of a nested query references an
attribute of a relation declared in the outer query, the two queries are
said to be correlated
 The result of a correlated nested query is different for each tuple

(or combination of tuples) of the relation(s) the outer query


 Query 12: Retrieve the name of each employee who has a dependent
with the same first name as the employee.

Q12: SELECT E.FNAME, E.LNAME


FROM EMPLOYEE AS E
WHERE E.SSN IN
(SELECT ESSN
FROM DEPENDENT
WHERE ESSN=E.SSN AND
E.FNAME=DEPENDENT_NAME)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 122


CORRELATED NESTED QUERIES
(contd.)
 In Q12, the nested query has a different result in the outer
query
 A query written with nested SELECT... FROM... WHERE...
blocks and using the = or IN comparison operators can
always be expressed as a single block query. For
example, Q12 may be written as in Q12A

Q12A: SELECT E.FNAME, E.LNAME


FROM EMPLOYEE E, DEPENDENT D
WHERE E.SSN=D.ESSN AND

E.FNAME=D.DEPENDENT_NAME

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 123


CORRELATED NESTED QUERIES
(contd.)
 The original SQL as specified for SYSTEM R also had a
CONTAINS comparison operator, which is used in
conjunction with nested correlated queries
 This operator was dropped from the language, possibly
because of the difficulty in implementing it efficiently
 Most implementations of SQL do not have this operator
 The CONTAINS operator compares two sets of values, and
returns TRUE if one set contains all values in the other set
 Reminiscent of the division operation of algebra

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 124


CORRELATED NESTED QUERIES
(contd.)
 Query 3: Retrieve the name of each employee who works
on all the projects controlled by department number 5.

Q3: SELECT FNAME, LNAME


FROM EMPLOYEE
WHERE ( (SELECT PNO
FROM WORKS_ON
WHERE SSN=ESSN)
CONTAINS
(SELECT PNUMBER
FROM PROJECT
WHERE DNUM=5) )

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 125


CORRELATED NESTED QUERIES
(contd.)
 In Q3, the second nested query, which is not
correlated with the outer query, retrieves the
project numbers of all projects controlled by
department 5
 The first nested query, which is correlated,
retrieves the project numbers on which the
employee works, which is different for each
employee tuple because of the correlation

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 126


Summary of SQL Queries (contd.)
 The SELECT-clause lists the attributes or functions to be retrieved
 The FROM-clause specifies all relations (or aliases) needed in the
query but not those needed in nested queries
 The WHERE-clause specifies the conditions for selection and join of
tuples from the relations specified in the FROM-clause
 GROUP BY specifies grouping attributes
 HAVING specifies a condition for selection of groups
 ORDER BY specifies an order for displaying the result of a query
 A query is evaluated by first applying the WHERE-clause, then

GROUP BY and HAVING, and finally the SELECT-clause

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 127

You might also like