0% found this document useful (0 votes)
2 views

L3 sql

The document outlines the course CS315: Database Systems, focusing on Structured Query Language (SQL) as a data manipulation and definition language for relational databases. It covers SQL's basic structure, data types, constraints, and examples of creating and modifying relation schemas, as well as querying data. The course is taught by Arnab Bhattacharya at the Indian Institute of Technology, Kanpur during the 2024-25 academic year.

Uploaded by

adijagdale101
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

L3 sql

The document outlines the course CS315: Database Systems, focusing on Structured Query Language (SQL) as a data manipulation and definition language for relational databases. It covers SQL's basic structure, data types, constraints, and examples of creating and modifying relation schemas, as well as querying data. The course is taught by Arnab Bhattacharya at the Indian Institute of Technology, Kanpur during the 2024-25 academic year.

Uploaded by

adijagdale101
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 202

CS315: DATABASE S YSTEMS

S TRUCTURED Q UERY L ANGUAGE (SQL)

Arnab Bhattacharya
[email protected]

Computer Science and Engineering,


Indian Institute of Technology, Kanpur
http://web.cse.iitk.ac.in/˜cs315/

2nd semester, 2024-25


Tue, Wed 12:00-13:15

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 1 / 52


Structured Query Language (SQL)
SQL is a querying language for relational databases

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 2 / 52


Structured Query Language (SQL)
SQL is a querying language for relational databases
Is a data manipulation language (DML)
Can access and manipulate data stored as a particular data model

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 2 / 52


Structured Query Language (SQL)
SQL is a querying language for relational databases
Is a data manipulation language (DML)
Can access and manipulate data stored as a particular data model
Declarative language
Specifies what to do, but not how to do

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 2 / 52


Structured Query Language (SQL)
SQL is a querying language for relational databases
Is a data manipulation language (DML)
Can access and manipulate data stored as a particular data model
Declarative language
Specifies what to do, but not how to do
Is also a data definition language (DDL)
Defines database relations and schemas

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 2 / 52


Structured Query Language (SQL)
SQL is a querying language for relational databases
Is a data manipulation language (DML)
Can access and manipulate data stored as a particular data model
Declarative language
Specifies what to do, but not how to do
Is also a data definition language (DDL)
Defines database relations and schemas
SQL has evolved widely after its first inception
Supports lots of extra operations that are non-standard

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 2 / 52


Example Schema
course (code, title, ctype, webpage)
coursetype (ctype, dept)
faculty (fid, name, dept, designation)
department (deptid, name)
semester (yr, half)
offering (coursecode, yr, half, instructor )
student (roll, name, dept, cpi)
program (roll, ptype)
registration (coursecode, roll, yr, half, gradecode)
grade (gradecode, value)

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 3 / 52


Creating Relation Schemas
create table: create table
r (A1 D1 C1 , . . . , An Dn Cn , (IC1 ), . . . , (ICk ))
r is the name of the relation
Each Ai is an attribute name whose data type or domain is
specified by Di
Ci specifies constraints or settings (if any)
ICj represents integrity constraints (if any)
Example
create t a b l e f a c u l t y (
f i d i n t e g e r primary key ,
name varchar ( 5 0 ) not n u l l ,
dept integer ,
d e s i g n a t i o n varchar ( 3 )
);

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 4 / 52


Data Types in SQL
char(n): fixed-length character string
varchar(n): variable-length character string, up to n
integer or int: integer
smallint: short integer
numeric(n,d): floating-point number with a total of n digits of which
d is after the decimal point
real: single-precision floating-point number
double precision: double-precision floating-point number
float(n): floating-point number with at least n digits

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 5 / 52


Data Types in SQL
char(n): fixed-length character string
varchar(n): variable-length character string, up to n
integer or int: integer
smallint: short integer
numeric(n,d): floating-point number with a total of n digits of which
d is after the decimal point
real: single-precision floating-point number
double precision: double-precision floating-point number
float(n): floating-point number with at least n digits
date: yyyy-mm-dd format
time: hh:mm:ss format
time(i): hh:mm:ss:i. . . i format with additional i digits for fraction of
a second
timestamp: both date and time
interval: relative value in either year-month or day-time format
Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 5 / 52
Other Data Types

User-defined data type


create type c p i as numeric ( 3 , 1 ) ;

Large objects such as images, videos, strings can be stored as


blob: binary large object
clob: character large object
A pointer to the object is stored in the relation, and not the object
itself

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 6 / 52


Other Data Types

User-defined data type


create type c p i as numeric ( 3 , 1 ) ;

Large objects such as images, videos, strings can be stored as


blob: binary large object
clob: character large object
A pointer to the object is stored in the relation, and not the object
itself
User-defined domain
create domain name as varchar ( 5 0 ) not n u l l ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 6 / 52


Constraints

Can be specified for each attribute as well as separately


not null: the attribute cannot be null
Requires some value while inserting as otherwise null is the default
primary key (Ai , . . . , Aj ): automatically ensures not null
default n: defaults to n if no value is specified
unique: specifies that this is a candidate key
foreign key: specifies as a foreign key and the relation it refers to
check P: predicate P must be satisfied
create t a b l e f a c u l t y (
f i d integer ,
name varchar ( 5 0 ) not n u l l ,
dept integer ,
d e s i g n a t i o n varchar ( 3 ) d e f a u l t ‘ ‘ AP ’ ’ ,
primary key f i d ,
f o r e i g n key ( dept ) references department ( dept ) ,
check ( f i d >= 0 )
);

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 7 / 52


Deleting or Modifying a Relation Schema

drop table: drop table r deletes the table from the database
Must satisfy other constraints already applied
Example
drop t a b l e f a c u l t y ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 8 / 52


Deleting or Modifying a Relation Schema

drop table: drop table r deletes the table from the database
Must satisfy other constraints already applied
Example
drop t a b l e f a c u l t y ;

alter table: alter table r add A D C


Adds attribute A with data type D at the end
C specifies constraints on A (if any)
Must satisfy other constraints already applied
alter table: alter table r drop A
Deletes attribute A from all tuples
Must satisfy other constraints already applied
Example
a l t e r t a b l e f a c u l t y add room varchar ( 1 0 ) ;
a l t e r t a b l e course drop webpage ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 8 / 52


Basic Query Structure

SQL is based on relational algebra


A basic SQL query is of the form
select A1 , . . . , An
from r1 , . . . , rm
where P
Each ri is a relation
Each Aj is an attribute from one of r1 , . . . , rm
P is a predicate involving attributes and constants
where can be left out, which then means true
Result is a relation with the schema (A1 , . . . , An )

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 9 / 52


Basic Query Structure

SQL is based on relational algebra


A basic SQL query is of the form
select A1 , . . . , An
from r1 , . . . , rm
where P
Each ri is a relation
Each Aj is an attribute from one of r1 , . . . , rm
P is a predicate involving attributes and constants
where can be left out, which then means true
Result is a relation with the schema (A1 , . . . , An )
Is equivalent to the relational algebra query

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 9 / 52


Basic Query Structure

SQL is based on relational algebra


A basic SQL query is of the form
select A1 , . . . , An
from r1 , . . . , rm
where P
Each ri is a relation
Each Aj is an attribute from one of r1 , . . . , rm
P is a predicate involving attributes and constants
where can be left out, which then means true
Result is a relation with the schema (A1 , . . . , An )
Is equivalent to the relational algebra query
ΠA1 ,...,An (σP (r1 × · · · × rm ))

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 9 / 52


Multisets

SQL relations are multisets or bags of tuples and not sets


Consequently, there may be two identical tuples
This is the biggest distinction with relational algebra

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 10 / 52


Multisets

SQL relations are multisets or bags of tuples and not sets


Consequently, there may be two identical tuples
This is the biggest distinction with relational algebra
Set behavior can be enforced by the keyword unique
In a query, keyword distinct achieves the same effect
Opposite is keyword all, which is default

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 10 / 52


Select

Lists attributes in the final output

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 11 / 52


Select

Lists attributes in the final output


Example: Find codes of courses offered in 2018

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 11 / 52


Select

Lists attributes in the final output


Example: Find codes of courses offered in 2018
s e l e c t coursecode
from o f f e r i n g
where y r = 2018;

Case-insensitive
select * chooses all attributes
To eliminate duplicates, use select distinct . . .
Otherwise, by default is select all . . .

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 11 / 52


Select

Lists attributes in the final output


Example: Find codes of courses offered in 2018
s e l e c t coursecode
from o f f e r i n g
where y r = 2018;

Case-insensitive
select * chooses all attributes
To eliminate duplicates, use select distinct . . .
Otherwise, by default is select all . . .
Can contain arithmetic expressions
s e l e c t coursecode , y r − 1959
from o f f e r i n g
where y r = 2018;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 11 / 52


From

Lists relations from where attributes will be listed


Corresponds to Cartesian product of the relations

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 12 / 52


From

Lists relations from where attributes will be listed


Corresponds to Cartesian product of the relations
Example: Find title of courses offered in 2018

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 12 / 52


From

Lists relations from where attributes will be listed


Corresponds to Cartesian product of the relations
Example: Find title of courses offered in 2018
select t i t l e
from course , o f f e r i n g
where course . code = o f f e r i n g . coursecode and y r = 2018;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 12 / 52


From

Lists relations from where attributes will be listed


Corresponds to Cartesian product of the relations
Example: Find title of courses offered in 2018
select t i t l e
from course , o f f e r i n g
where course . code = o f f e r i n g . coursecode and y r = 2018;

When two relations contain attributes of the same name,


qualification is needed to remove ambiguity
Example: Find name of students in B.Tech. program

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 12 / 52


From

Lists relations from where attributes will be listed


Corresponds to Cartesian product of the relations
Example: Find title of courses offered in 2018
select t i t l e
from course , o f f e r i n g
where course . code = o f f e r i n g . coursecode and y r = 2018;

When two relations contain attributes of the same name,


qualification is needed to remove ambiguity
Example: Find name of students in B.Tech. program
s e l e c t s t u d e n t . name
from s t u d e n t , program
where s t u d e n t . r o l l = program . r o l l and program . ptype =
‘ ‘ B . Tech . ’ ’ ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 12 / 52


Where
Specifies conditions that the result tuples must satisfy

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 13 / 52


Where
Specifies conditions that the result tuples must satisfy
Example
s e l e c t coursecode
from o f f e r i n g
where y r = 2018;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 13 / 52


Where
Specifies conditions that the result tuples must satisfy
Example
s e l e c t coursecode
from o f f e r i n g
where y r = 2018;

May use and, or and not to connect predicates


s e l e c t coursecode
from o f f e r i n g
where y r = 2018 and i n s t r u c t o r = 1 0 ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 13 / 52


Where
Specifies conditions that the result tuples must satisfy
Example
s e l e c t coursecode
from o f f e r i n g
where y r = 2018;

May use and, or and not to connect predicates


s e l e c t coursecode
from o f f e r i n g
where y r = 2018 and i n s t r u c t o r = 1 0 ;

Unused clause is equivalent to where true


s e l e c t coursecode
from o f f e r i n g ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 13 / 52


Where
Specifies conditions that the result tuples must satisfy
Example
s e l e c t coursecode
from o f f e r i n g
where y r = 2018;

May use and, or and not to connect predicates


s e l e c t coursecode
from o f f e r i n g
where y r = 2018 and i n s t r u c t o r = 1 0 ;

Unused clause is equivalent to where true


s e l e c t coursecode
from o f f e r i n g ;

SQL allows between operator (includes both)


s e l e c t coursecode
from o f f e r i n g
where y r between 2016 and 2018;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 13 / 52


Rename Operation

SQL allows renaming of relations and attributes to remove


ambiguity
Keyword as is used
Example
s e l e c t s t u d e n t . r o l l as r o l l n u m b e r
from s t u d e n t , program
where s t u d e n t . r o l l = program . r o l l and program . ptype =
‘ ‘ B . Tech . ’ ’ ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 14 / 52


Rename Operation

SQL allows renaming of relations and attributes to remove


ambiguity
Keyword as is used
Example
s e l e c t s t u d e n t . r o l l as r o l l n u m b e r
from s t u d e n t , program
where s t u d e n t . r o l l = program . r o l l and program . ptype =
‘ ‘ B . Tech . ’ ’ ;

Renaming is necessary when the same relation needs to be used


twice
Example: Find names of students whose cpi is greater than that of
“ABC”

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 14 / 52


Rename Operation

SQL allows renaming of relations and attributes to remove


ambiguity
Keyword as is used
Example
s e l e c t s t u d e n t . r o l l as r o l l n u m b e r
from s t u d e n t , program
where s t u d e n t . r o l l = program . r o l l and program . ptype =
‘ ‘ B . Tech . ’ ’ ;

Renaming is necessary when the same relation needs to be used


twice
Example: Find names of students whose cpi is greater than that of
“ABC”
s e l e c t T . name
from s t u d e n t as T , s t u d e n t as S
where T . c p i > S . c p i and S . name = ‘ ‘ABC ’ ’ ;

as can be omitted by simply stating student T


Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 14 / 52
String Operations
Supports string matching in addition to equality of two strings
Uses like to match patterns specified using special characters
: matches any character
%: matches any substring

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 15 / 52


String Operations
Supports string matching in addition to equality of two strings
Uses like to match patterns specified using special characters
: matches any character
%: matches any substring
Example: Find all departments having “Engineering” in its name

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 15 / 52


String Operations
Supports string matching in addition to equality of two strings
Uses like to match patterns specified using special characters
: matches any character
%: matches any substring
Example: Find all departments having “Engineering” in its name
select *
from department
where name l i k e ‘ ‘% E n g i n e e r i n g% ’ ’ ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 15 / 52


String Operations
Supports string matching in addition to equality of two strings
Uses like to match patterns specified using special characters
: matches any character
%: matches any substring
Example: Find all departments having “Engineering” in its name
select *
from department
where name l i k e ‘ ‘% E n g i n e e r i n g% ’ ’ ;

Example: Find departments with the name “?E”

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 15 / 52


String Operations
Supports string matching in addition to equality of two strings
Uses like to match patterns specified using special characters
: matches any character
%: matches any substring
Example: Find all departments having “Engineering” in its name
select *
from department
where name l i k e ‘ ‘% E n g i n e e r i n g% ’ ’ ;

Example: Find departments with the name “?E”


select *
from department
where name l i k e ‘ ‘ E ’ ’ ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 15 / 52


String Operations
Supports string matching in addition to equality of two strings
Uses like to match patterns specified using special characters
: matches any character
%: matches any substring
Example: Find all departments having “Engineering” in its name
select *
from department
where name l i k e ‘ ‘% E n g i n e e r i n g% ’ ’ ;

Example: Find departments with the name “?E”


select *
from department
where name l i k e ‘ ‘ E ’ ’ ;

Example: Find the department whose name is “ E”

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 15 / 52


String Operations
Supports string matching in addition to equality of two strings
Uses like to match patterns specified using special characters
: matches any character
%: matches any substring
Example: Find all departments having “Engineering” in its name
select *
from department
where name l i k e ‘ ‘% E n g i n e e r i n g% ’ ’ ;

Example: Find departments with the name “?E”


select *
from department
where name l i k e ‘ ‘ E ’ ’ ;

Example: Find the department whose name is “ E”


select *
from department
where name = ‘ ‘ E ’ ’ ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 15 / 52


Ordering of Tuples

Tuples in the final relation can be ordered using order by

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 16 / 52


Ordering of Tuples

Tuples in the final relation can be ordered using order by


For display purposes only and has no actual effect
Example: Order departments by name

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 16 / 52


Ordering of Tuples

Tuples in the final relation can be ordered using order by


For display purposes only and has no actual effect
Example: Order departments by name
select *
from department
order by name ;

Use desc to obtain tuples in descending order


select *
from department
order by name desc ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 16 / 52


Ordering of Tuples

Tuples in the final relation can be ordered using order by


For display purposes only and has no actual effect
Example: Order departments by name
select *
from department
order by name ;

Use desc to obtain tuples in descending order


select *
from department
order by name desc ;

Default is ascending order (asc)

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 16 / 52


Set Operations

Operators union, intersect and except correspond to ∪, ∩, −


Eliminates duplicates
For multiset operations, i.e., to retain duplicates, use all after the
operations
Example: Find names of all faculty members and students

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 17 / 52


Set Operations

Operators union, intersect and except correspond to ∪, ∩, −


Eliminates duplicates
For multiset operations, i.e., to retain duplicates, use all after the
operations
Example: Find names of all faculty members and students
( s e l e c t name from f a c u l t y )
union
( s e l e c t name from s t u d e n t ) ;

Example: Find names of faculty members not found in students

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 17 / 52


Set Operations

Operators union, intersect and except correspond to ∪, ∩, −


Eliminates duplicates
For multiset operations, i.e., to retain duplicates, use all after the
operations
Example: Find names of all faculty members and students
( s e l e c t name from f a c u l t y )
union
( s e l e c t name from s t u d e n t ) ;

Example: Find names of faculty members not found in students


( s e l e c t name from f a c u l t y )
except
( s e l e c t name from s t u d e n t ) ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 17 / 52


Aggregate Functions

Five operations that work on multisets: avg, min, max, sum, count
Example: Find the average cpi of students

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 18 / 52


Aggregate Functions

Five operations that work on multisets: avg, min, max, sum, count
Example: Find the average cpi of students
s e l e c t avg ( c p i )
from s t u d e n t ;

For set operations, use distinct


Example: Find the total number of students

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 18 / 52


Aggregate Functions

Five operations that work on multisets: avg, min, max, sum, count
Example: Find the average cpi of students
s e l e c t avg ( c p i )
from s t u d e n t ;

For set operations, use distinct


Example: Find the total number of students
s e l e c t count ( d i s t i n c t r o l l )
from s t u d e n t ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 18 / 52


Grouping

To apply aggregate operations on separate groups, use group by


The aggregate operator is applied on each group separately
Example: Find the number of students in each department

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 19 / 52


Grouping

To apply aggregate operations on separate groups, use group by


The aggregate operator is applied on each group separately
Example: Find the number of students in each department
s e l e c t dept , count ( d i s t i n c t r o l l )
from s t u d e n t
group by dept ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 19 / 52


Grouping

To apply aggregate operations on separate groups, use group by


The aggregate operator is applied on each group separately
Example: Find the number of students in each department
s e l e c t dept , count ( d i s t i n c t r o l l )
from s t u d e n t
group by dept ;

Attributes in select clause outside of aggregate functions must


appear in group by list

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 19 / 52


Qualifying Groups
In order to select certain groups, use having clause
Only those groups satisfying having clause appear in the result
Example: Find average grade in each course where number of
students is at least 5

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 20 / 52


Qualifying Groups
In order to select certain groups, use having clause
Only those groups satisfying having clause appear in the result
Example: Find average grade in each course where number of
students is at least 5
s e l e c t coursecode , avg ( grade )
from r e g i s t r a t i o n
group by coursecode
having count ( r o l l ) >= 5 ;

The predicate in having is applied after forming groups whereas


the predicate in where is applied before doing so

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 20 / 52


Qualifying Groups
In order to select certain groups, use having clause
Only those groups satisfying having clause appear in the result
Example: Find average grade in each course where number of
students is at least 5
s e l e c t coursecode , avg ( grade )
from r e g i s t r a t i o n
group by coursecode
having count ( r o l l ) >= 5 ;

The predicate in having is applied after forming groups whereas


the predicate in where is applied before doing so
Example: Find average grade in each course of type 4 where
number of students is at least 5

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 20 / 52


Qualifying Groups
In order to select certain groups, use having clause
Only those groups satisfying having clause appear in the result
Example: Find average grade in each course where number of
students is at least 5
s e l e c t coursecode , avg ( grade )
from r e g i s t r a t i o n
group by coursecode
having count ( r o l l ) >= 5 ;

The predicate in having is applied after forming groups whereas


the predicate in where is applied before doing so
Example: Find average grade in each course of type 4 where
number of students is at least 5
s e l e c t coursecode , avg ( grade )
from r e g i s t r a t i o n , course
where r e g i s t r a t i o n . coursecode = course . code and c t y p e = 4
group by coursecode
having count ( r o l l ) >= 5 ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 20 / 52


Null

null signifies missing or unknown value


The predicates is null and is not null can be used to check for null
values
Example: find courses that do not have a webpage

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 21 / 52


Null

null signifies missing or unknown value


The predicates is null and is not null can be used to check for null
values
Example: find courses that do not have a webpage
s e l e c t code
from course
where webpage i s n u l l ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 21 / 52


Null

null signifies missing or unknown value


The predicates is null and is not null can be used to check for null
values
Example: find courses that do not have a webpage
s e l e c t code
from course
where webpage i s n u l l ;

Result of expressions involving null evaluate to null


Comparison with null returns unknown
Uses same three-valued logic as relational algebra
Aggregate functions ignore null
count(*) does not ignore nulls

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 21 / 52


Nested Subqueries

A query that occurs in the where or from clause of another query


is called a subquery
Entire query is called outer query while the subquery is called
inner query or nested query
Used in tests for set membership, set cardinality, set comparisons

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 22 / 52


Set Membership

Keyword in is used for set membership tests


Example: Find faculty members who have not offered any course

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 23 / 52


Set Membership

Keyword in is used for set membership tests


Example: Find faculty members who have not offered any course
select *
from f a c u l t y
where f i d not i n (
select i n s t r u c t o r
from o f f e r i n g ) ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 23 / 52


Scoping of Attributes
It is always a good practice to qualify attributes
It is better to rename relations if it is used in both the outer and the
inner queries

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 24 / 52


Scoping of Attributes
It is always a good practice to qualify attributes
It is better to rename relations if it is used in both the outer and the
inner queries
An unqualified attribute refers to the innermost query

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 24 / 52


Scoping of Attributes
It is always a good practice to qualify attributes
It is better to rename relations if it is used in both the outer and the
inner queries
An unqualified attribute refers to the innermost query
When a nested query refers to an attribute in the outer query, it is
called a correlated query
Example: Find names of all students who have taken course with
an instructor with the same name

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 24 / 52


Scoping of Attributes
It is always a good practice to qualify attributes
It is better to rename relations if it is used in both the outer and the
inner queries
An unqualified attribute refers to the innermost query
When a nested query refers to an attribute in the outer query, it is
called a correlated query
Example: Find names of all students who have taken course with
an instructor with the same name
s e l e c t s t u d e n t . name
from r e g i s t r a t i o n as R, s t u d e n t as S , f a c u l t y as F
where S . r o l l = R . r o l l and S . name = F . name and F . f i d i n (
select i n s t r u c t o r
from o f f e r i n g
where o f f e r i n g . coursecode = R. coursecode ) ;

Inner query is evaluated for each tuple in the outer query

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 24 / 52


Correlated Queries
s e l e c t S . name
from r e g i s t r a t i o n as R, s t u d e n t as S , f a c u l t y as F
where S . r o l l = R . r o l l and S . name = F . name and F . f i d i n (
s e l e c t O. i n s t r u c t o r
from o f f e r i n g as O
where O. coursecode = R. coursecode ) ;
student faculty registration
roll name fid name coursecode roll
11 AB 101 AB 1 11
12 CD 102 EF 2 12
13 EF 103 GH 3 13

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 25 / 52


Correlated Queries
s e l e c t S . name
from r e g i s t r a t i o n as R, s t u d e n t as S , f a c u l t y as F
where S . r o l l = R . r o l l and S . name = F . name and F . f i d i n (
s e l e c t O. i n s t r u c t o r
from o f f e r i n g as O
where O. coursecode = R. coursecode ) ;
student faculty registration
roll name fid name coursecode roll
11 AB 101 AB 1 11
12 CD 102 EF 2 12
13 EF 103 GH 3 13
(R.roll = S.roll and S.name = F.name)(R × S × F)
R.coursecode R.roll S.roll S.name F.fid F.name
1 11 11 AB 101 AB
3 13 13 EF 102 EF

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 25 / 52


Evaluation Per Tuple
s e l e c t S . name
from r e g i s t r a t i o n as R, s t u d e n t as S , f a c u l t y as F
where S . r o l l = R . r o l l and S . name = F . name and F . f i d i n (
s e l e c t O. i n s t r u c t o r
from o f f e r i n g as O
where O. coursecode = R. coursecode ) ;
offering
R.roll = S.roll and S.name = F.name
O.coursecode instructor
R.coursecode roll name F.fid
1 101
1 11 AB 101
2 102
3 13 EF 102
3 103
⟨1, 11, AB, 101⟩

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 26 / 52


Evaluation Per Tuple
s e l e c t S . name
from r e g i s t r a t i o n as R, s t u d e n t as S , f a c u l t y as F
where S . r o l l = R . r o l l and S . name = F . name and F . f i d i n (
s e l e c t O. i n s t r u c t o r
from o f f e r i n g as O
where O. coursecode = R. coursecode ) ;
offering
R.roll = S.roll and S.name = F.name
O.coursecode instructor
R.coursecode roll name F.fid
1 101
1 11 AB 101
2 102
3 13 EF 102
3 103
⟨1, 11, AB, 101⟩
With R.coursecode = 1, offering chooses only instructor {101}

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 26 / 52


Evaluation Per Tuple
s e l e c t S . name
from r e g i s t r a t i o n as R, s t u d e n t as S , f a c u l t y as F
where S . r o l l = R . r o l l and S . name = F . name and F . f i d i n (
s e l e c t O. i n s t r u c t o r
from o f f e r i n g as O
where O. coursecode = R. coursecode ) ;
offering
R.roll = S.roll and S.name = F.name
O.coursecode instructor
R.coursecode roll name F.fid
1 101
1 11 AB 101
2 102
3 13 EF 102
3 103
⟨1, 11, AB, 101⟩
With R.coursecode = 1, offering chooses only instructor {101}
Now, since fid = 101 ∈ {101}, tuple is returned

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 26 / 52


Evaluation Per Tuple
s e l e c t S . name
from r e g i s t r a t i o n as R, s t u d e n t as S , f a c u l t y as F
where S . r o l l = R . r o l l and S . name = F . name and F . f i d i n (
s e l e c t O. i n s t r u c t o r
from o f f e r i n g as O
where O. coursecode = R. coursecode ) ;
offering
R.roll = S.roll and S.name = F.name
O.coursecode instructor
R.coursecode roll name F.fid
1 101
1 11 AB 101
2 102
3 13 EF 102
3 103
⟨1, 11, AB, 101⟩
With R.coursecode = 1, offering chooses only instructor {101}
Now, since fid = 101 ∈ {101}, tuple is returned
⟨3, 13, EF , 102⟩

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 26 / 52


Evaluation Per Tuple
s e l e c t S . name
from r e g i s t r a t i o n as R, s t u d e n t as S , f a c u l t y as F
where S . r o l l = R . r o l l and S . name = F . name and F . f i d i n (
s e l e c t O. i n s t r u c t o r
from o f f e r i n g as O
where O. coursecode = R. coursecode ) ;
offering
R.roll = S.roll and S.name = F.name
O.coursecode instructor
R.coursecode roll name F.fid
1 101
1 11 AB 101
2 102
3 13 EF 102
3 103
⟨1, 11, AB, 101⟩
With R.coursecode = 1, offering chooses only instructor {101}
Now, since fid = 101 ∈ {101}, tuple is returned
⟨3, 13, EF , 102⟩
With R.coursecode = 3, offering chooses only instructor {103}

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 26 / 52


Evaluation Per Tuple
s e l e c t S . name
from r e g i s t r a t i o n as R, s t u d e n t as S , f a c u l t y as F
where S . r o l l = R . r o l l and S . name = F . name and F . f i d i n (
s e l e c t O. i n s t r u c t o r
from o f f e r i n g as O
where O. coursecode = R. coursecode ) ;
offering
R.roll = S.roll and S.name = F.name
O.coursecode instructor
R.coursecode roll name F.fid
1 101
1 11 AB 101
2 102
3 13 EF 102
3 103
⟨1, 11, AB, 101⟩
With R.coursecode = 1, offering chooses only instructor {101}
Now, since fid = 101 ∈ {101}, tuple is returned
⟨3, 13, EF , 102⟩
With R.coursecode = 3, offering chooses only instructor {103}
Now, since fid = 102 < {103}, tuple is not returned

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 26 / 52


Non-Correlated Query
s e l e c t S . name
from r e g i s t r a t i o n as R, s t u d e n t as S , f a c u l t y as F
where S . r o l l = R . r o l l and S . name = F . name and F . f i d i n (
s e l e c t O. i n s t r u c t o r
from o f f e r i n g as O, r e g i s t r a t i o n as G
where O. coursecode = G. coursecode ) ;
Inner query
R.roll = S.roll and S.name = F.name
O.instructor
R.coursecode roll name F.fid
101
1 11 AB 101
102
3 13 EF 102
103
⟨1, 11, AB, 101⟩

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 27 / 52


Non-Correlated Query
s e l e c t S . name
from r e g i s t r a t i o n as R, s t u d e n t as S , f a c u l t y as F
where S . r o l l = R . r o l l and S . name = F . name and F . f i d i n (
s e l e c t O. i n s t r u c t o r
from o f f e r i n g as O, r e g i s t r a t i o n as G
where O. coursecode = G. coursecode ) ;
Inner query
R.roll = S.roll and S.name = F.name
O.instructor
R.coursecode roll name F.fid
101
1 11 AB 101
102
3 13 EF 102
103
⟨1, 11, AB, 101⟩
Since fid = 101 ∈ {101, 102, 103}, tuple is returned

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 27 / 52


Non-Correlated Query
s e l e c t S . name
from r e g i s t r a t i o n as R, s t u d e n t as S , f a c u l t y as F
where S . r o l l = R . r o l l and S . name = F . name and F . f i d i n (
s e l e c t O. i n s t r u c t o r
from o f f e r i n g as O, r e g i s t r a t i o n as G
where O. coursecode = G. coursecode ) ;
Inner query
R.roll = S.roll and S.name = F.name
O.instructor
R.coursecode roll name F.fid
101
1 11 AB 101
102
3 13 EF 102
103
⟨1, 11, AB, 101⟩
Since fid = 101 ∈ {101, 102, 103}, tuple is returned
⟨3, 13, EF , 102⟩

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 27 / 52


Non-Correlated Query
s e l e c t S . name
from r e g i s t r a t i o n as R, s t u d e n t as S , f a c u l t y as F
where S . r o l l = R . r o l l and S . name = F . name and F . f i d i n (
s e l e c t O. i n s t r u c t o r
from o f f e r i n g as O, r e g i s t r a t i o n as G
where O. coursecode = G. coursecode ) ;
Inner query
R.roll = S.roll and S.name = F.name
O.instructor
R.coursecode roll name F.fid
101
1 11 AB 101
102
3 13 EF 102
103
⟨1, 11, AB, 101⟩
Since fid = 101 ∈ {101, 102, 103}, tuple is returned
⟨3, 13, EF , 102⟩
Since fid = 102 ∈ {101, 102, 103}, tuple is returned

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 27 / 52


Non-Correlated Query
s e l e c t S . name
from r e g i s t r a t i o n as R, s t u d e n t as S , f a c u l t y as F
where S . r o l l = R . r o l l and S . name = F . name and F . f i d i n (
s e l e c t O. i n s t r u c t o r
from o f f e r i n g as O, r e g i s t r a t i o n as G
where O. coursecode = G. coursecode ) ;
Inner query
R.roll = S.roll and S.name = F.name
O.instructor
R.coursecode roll name F.fid
101
1 11 AB 101
102
3 13 EF 102
103
⟨1, 11, AB, 101⟩
Since fid = 101 ∈ {101, 102, 103}, tuple is returned
⟨3, 13, EF , 102⟩
Since fid = 102 ∈ {101, 102, 103}, tuple is returned
Thus, non-correlated query results in an error

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 27 / 52


Set Comparison: some

(F ⟨comp⟩ some r ) ⇔ (∃t ∈ r (F ⟨comp⟩t))


Examples:
5 < some{0, 5, 6} =

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 28 / 52


Set Comparison: some

(F ⟨comp⟩ some r ) ⇔ (∃t ∈ r (F ⟨comp⟩t))


Examples:
5 < some{0, 5, 6} = true
5 < some{0, 5} =

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 28 / 52


Set Comparison: some

(F ⟨comp⟩ some r ) ⇔ (∃t ∈ r (F ⟨comp⟩t))


Examples:
5 < some{0, 5, 6} = true
5 < some{0, 5} = false
5 = some{0, 5} =

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 28 / 52


Set Comparison: some

(F ⟨comp⟩ some r ) ⇔ (∃t ∈ r (F ⟨comp⟩t))


Examples:
5 < some{0, 5, 6} = true
5 < some{0, 5} = false
5 = some{0, 5} = true
5 , some{0, 5} =

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 28 / 52


Set Comparison: some

(F ⟨comp⟩ some r ) ⇔ (∃t ∈ r (F ⟨comp⟩t))


Examples:
5 < some{0, 5, 6} = true
5 < some{0, 5} = false
5 = some{0, 5} = true
5 , some{0, 5} = true

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 28 / 52


Set Comparison: some

(F ⟨comp⟩ some r ) ⇔ (∃t ∈ r (F ⟨comp⟩t))


Examples:
5 < some{0, 5, 6} = true
5 < some{0, 5} = false
5 = some{0, 5} = true
5 , some{0, 5} = true
(= some) ≡ (in)
(, some) . (not in)

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 28 / 52


Set Comparison: some

(F ⟨comp⟩ some r ) ⇔ (∃t ∈ r (F ⟨comp⟩t))


Examples:
5 < some{0, 5, 6} = true
5 < some{0, 5} = false
5 = some{0, 5} = true
5 , some{0, 5} = true
(= some) ≡ (in)
(, some) . (not in)
Example: Find roll numbers of students who have CPI greater
than some student in “CSE”

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 28 / 52


Set Comparison: some

(F ⟨comp⟩ some r ) ⇔ (∃t ∈ r (F ⟨comp⟩t))


Examples:
5 < some{0, 5, 6} = true
5 < some{0, 5} = false
5 = some{0, 5} = true
5 , some{0, 5} = true
(= some) ≡ (in)
(, some) . (not in)
Example: Find roll numbers of students who have CPI greater
than some student in “CSE”
select r o l l
from s t u d e n t
where c p i > some (
select cpi
from s t u d e n t
where dept = ‘ ‘CSE ’ ’ ) ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 28 / 52


Set Comparison: all

(F ⟨comp⟩ all r ) ⇔ (∀t ∈ r (F ⟨comp⟩t))


Examples:
5 < all{0, 5, 6} =

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 29 / 52


Set Comparison: all

(F ⟨comp⟩ all r ) ⇔ (∀t ∈ r (F ⟨comp⟩t))


Examples:
5 < all{0, 5, 6} = false
5 < all{6, 9} =

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 29 / 52


Set Comparison: all

(F ⟨comp⟩ all r ) ⇔ (∀t ∈ r (F ⟨comp⟩t))


Examples:
5 < all{0, 5, 6} = false
5 < all{6, 9} = true
5 = all{0, 5} =

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 29 / 52


Set Comparison: all

(F ⟨comp⟩ all r ) ⇔ (∀t ∈ r (F ⟨comp⟩t))


Examples:
5 < all{0, 5, 6} = false
5 < all{6, 9} = true
5 = all{0, 5} = false
5 , all{4, 6} =

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 29 / 52


Set Comparison: all

(F ⟨comp⟩ all r ) ⇔ (∀t ∈ r (F ⟨comp⟩t))


Examples:
5 < all{0, 5, 6} = false
5 < all{6, 9} = true
5 = all{0, 5} = false
5 , all{4, 6} = true

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 29 / 52


Set Comparison: all

(F ⟨comp⟩ all r ) ⇔ (∀t ∈ r (F ⟨comp⟩t))


Examples:
5 < all{0, 5, 6} = false
5 < all{6, 9} = true
5 = all{0, 5} = false
5 , all{4, 6} = true
(, all) ≡ (not in)
(= all) . (in)

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 29 / 52


Set Comparison: all

(F ⟨comp⟩ all r ) ⇔ (∀t ∈ r (F ⟨comp⟩t))


Examples:
5 < all{0, 5, 6} = false
5 < all{6, 9} = true
5 = all{0, 5} = false
5 , all{4, 6} = true
(, all) ≡ (not in)
(= all) . (in)
Example: Find roll numbers of students who have CPI greater
than all students in “CSE”

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 29 / 52


Set Comparison: all

(F ⟨comp⟩ all r ) ⇔ (∀t ∈ r (F ⟨comp⟩t))


Examples:
5 < all{0, 5, 6} = false
5 < all{6, 9} = true
5 = all{0, 5} = false
5 , all{4, 6} = true
(, all) ≡ (not in)
(= all) . (in)
Example: Find roll numbers of students who have CPI greater
than all students in “CSE”
select r o l l
from s t u d e n t
where c p i > a l l (
select cpi
from s t u d e n t
where dept = ‘ ‘CSE ’ ’ ) ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 29 / 52


Empty Set
exists tests if the relation is empty
(exists r ) ⇔ (r , Φ)
(not exists r ) ⇔ (r = Φ)

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 30 / 52


Empty Set
exists tests if the relation is empty
(exists r ) ⇔ (r , Φ)
(not exists r ) ⇔ (r = Φ)
Example: Find faculty members who have offered courses in 2018

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 30 / 52


Empty Set
exists tests if the relation is empty
(exists r ) ⇔ (r , Φ)
(not exists r ) ⇔ (r = Φ)
Example: Find faculty members who have offered courses in 2018
select f i d
from f a c u l t y F
where e x i s t s (
select i n s t r u c t o r
from o f f e r i n g O
where y r = 2018 and O. i n s t r u c t o r = F . f i d ) ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 30 / 52


Empty Set
exists tests if the relation is empty
(exists r ) ⇔ (r , Φ)
(not exists r ) ⇔ (r = Φ)
Example: Find faculty members who have offered courses in 2018
select f i d
from f a c u l t y F
where e x i s t s (
select i n s t r u c t o r
from o f f e r i n g O
where y r = 2018 and O. i n s t r u c t o r = F . f i d ) ;

Example: Find faculty members who have not offered courses in


2018

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 30 / 52


Empty Set
exists tests if the relation is empty
(exists r ) ⇔ (r , Φ)
(not exists r ) ⇔ (r = Φ)
Example: Find faculty members who have offered courses in 2018
select f i d
from f a c u l t y F
where e x i s t s (
select i n s t r u c t o r
from o f f e r i n g O
where y r = 2018 and O. i n s t r u c t o r = F . f i d ) ;

Example: Find faculty members who have not offered courses in


2018
...
where not e x i s t s (
... );

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 30 / 52


Duplication in Sets

unique tests if the relation contains duplicate tuples


(unique r ) ⇔ (∀t, s ∈ r (t , s))
(not unique r ) ⇔ (∃t, s ∈ r (t = s))

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 31 / 52


Duplication in Sets

unique tests if the relation contains duplicate tuples


(unique r ) ⇔ (∀t, s ∈ r (t , s))
(not unique r ) ⇔ (∃t, s ∈ r (t = s))
Example: Find faculty members who have only offered one course

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 31 / 52


Duplication in Sets

unique tests if the relation contains duplicate tuples


(unique r ) ⇔ (∀t, s ∈ r (t , s))
(not unique r ) ⇔ (∃t, s ∈ r (t = s))
Example: Find faculty members who have only offered one course
select f i d
from f a c u l t y as F
where unique (
s e l e c t coursecode
from o f f e r i n g O
where O. i n s t r u c t o r = F . f i d ) ;

Example: Find faculty members who have offered multiple courses

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 31 / 52


Duplication in Sets

unique tests if the relation contains duplicate tuples


(unique r ) ⇔ (∀t, s ∈ r (t , s))
(not unique r ) ⇔ (∃t, s ∈ r (t = s))
Example: Find faculty members who have only offered one course
select f i d
from f a c u l t y as F
where unique (
s e l e c t coursecode
from o f f e r i n g O
where O. i n s t r u c t o r = F . f i d ) ;

Example: Find faculty members who have offered multiple courses


...
where not unique (
... );

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 31 / 52


Explicit Sets

Use set literals specified within brackets


Example: Find students in “CSE” and “ECO”
select *
from s t u d e n t
where dept i n ( ‘ ‘ CSE ’ ’ , ‘ ‘ECO ’ ’ ) ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 32 / 52


Summary of SQL Query Format
May contain up to six clauses
May be nested
Only the first two, select and from, are mandatory
Format (in order)
select ⟨ attribute list ⟩
from ⟨ relation list ⟩
where ⟨ predicate or tuple condition ⟩
group by ⟨ group attribute list ⟩
having ⟨ group condition ⟩
order by ⟨ attribute list ⟩

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 33 / 52


Summary of SQL Query Format
May contain up to six clauses
May be nested
Only the first two, select and from, are mandatory
Format (in order)
select ⟨ attribute list ⟩
from ⟨ relation list ⟩
where ⟨ predicate or tuple condition ⟩
group by ⟨ group attribute list ⟩
having ⟨ group condition ⟩
order by ⟨ attribute list ⟩
Execution order

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 33 / 52


Summary of SQL Query Format
May contain up to six clauses
May be nested
Only the first two, select and from, are mandatory
Format (in order)
select ⟨ attribute list ⟩
from ⟨ relation list ⟩
where ⟨ predicate or tuple condition ⟩
group by ⟨ group attribute list ⟩
having ⟨ group condition ⟩
order by ⟨ attribute list ⟩
Execution order
1 from

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 33 / 52


Summary of SQL Query Format
May contain up to six clauses
May be nested
Only the first two, select and from, are mandatory
Format (in order)
select ⟨ attribute list ⟩
from ⟨ relation list ⟩
where ⟨ predicate or tuple condition ⟩
group by ⟨ group attribute list ⟩
having ⟨ group condition ⟩
order by ⟨ attribute list ⟩
Execution order
1 from
2 where

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 33 / 52


Summary of SQL Query Format
May contain up to six clauses
May be nested
Only the first two, select and from, are mandatory
Format (in order)
select ⟨ attribute list ⟩
from ⟨ relation list ⟩
where ⟨ predicate or tuple condition ⟩
group by ⟨ group attribute list ⟩
having ⟨ group condition ⟩
order by ⟨ attribute list ⟩
Execution order
1 from
2 where
3 group by

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 33 / 52


Summary of SQL Query Format
May contain up to six clauses
May be nested
Only the first two, select and from, are mandatory
Format (in order)
select ⟨ attribute list ⟩
from ⟨ relation list ⟩
where ⟨ predicate or tuple condition ⟩
group by ⟨ group attribute list ⟩
having ⟨ group condition ⟩
order by ⟨ attribute list ⟩
Execution order
1 from
2 where
3 group by
4 having

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 33 / 52


Summary of SQL Query Format
May contain up to six clauses
May be nested
Only the first two, select and from, are mandatory
Format (in order)
select ⟨ attribute list ⟩
from ⟨ relation list ⟩
where ⟨ predicate or tuple condition ⟩
group by ⟨ group attribute list ⟩
having ⟨ group condition ⟩
order by ⟨ attribute list ⟩
Execution order
1 from
2 where
3 group by
4 having
5 select

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 33 / 52


Summary of SQL Query Format
May contain up to six clauses
May be nested
Only the first two, select and from, are mandatory
Format (in order)
select ⟨ attribute list ⟩
from ⟨ relation list ⟩
where ⟨ predicate or tuple condition ⟩
group by ⟨ group attribute list ⟩
having ⟨ group condition ⟩
order by ⟨ attribute list ⟩
Execution order
1 from
2 where
3 group by
4 having
5 select
6 order by
Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 33 / 52
Derived Relations

In the from clause, a derived relation (result of a subquery) can be


used

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 34 / 52


Derived Relations

In the from clause, a derived relation (result of a subquery) can be


used
Example: Find departments and average CPIs where average CPI
is greater than 8.0

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 34 / 52


Derived Relations

In the from clause, a derived relation (result of a subquery) can be


used
Example: Find departments and average CPIs where average CPI
is greater than 8.0
select deptid , avg cpi
from (
s e l e c t dept , avg ( c p i )
from s t u d e n t
group by dept )
as dept avg ( d e p t i d , a v g c p i )
where a v g c p i >= 8 . 0 ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 34 / 52


Derived Relations

In the from clause, a derived relation (result of a subquery) can be


used
Example: Find departments and average CPIs where average CPI
is greater than 8.0
select deptid , avg cpi
from (
s e l e c t dept , avg ( c p i )
from s t u d e n t
group by dept )
as dept avg ( d e p t i d , a v g c p i )
where a v g c p i >= 8 . 0 ;

Avoids using having clause

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 34 / 52


With

with clause defines a temporary relation


This temporary relation is available only to the query using the
with clause

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 35 / 52


With

with clause defines a temporary relation


This temporary relation is available only to the query using the
with clause
Example: Find departments and average CPIs where average CPI
is greater than 8.0

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 35 / 52


With

with clause defines a temporary relation


This temporary relation is available only to the query using the
with clause
Example: Find departments and average CPIs where average CPI
is greater than 8.0
with dept avg ( d e p t i d , a v g c p i ) as
s e l e c t dept , avg ( c p i )
from s t u d e n t
group by dept
select deptid , avg cpi
from dept avg
where a v g c p i >= 8 . 0 ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 35 / 52


Insertion

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 36 / 52


Insertion

insert into . . . values statement

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 36 / 52


Insertion

insert into . . . values statement


Example: Create a new student “ABC” with roll 1897 and
department 7

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 36 / 52


Insertion

insert into . . . values statement


Example: Create a new student “ABC” with roll 1897 and
department 7
i n s e r t i n t o s t u d e n t ( r o l l , name , dept , c p i )
values (1897 , ‘ ‘ABC ’ ’ , 7 , 0 . 0 ) ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 36 / 52


Insertion

insert into . . . values statement


Example: Create a new student “ABC” with roll 1897 and
department 7
i n s e r t i n t o s t u d e n t ( r o l l , name , dept , c p i )
values (1897 , ‘ ‘ABC ’ ’ , 7 , 0 . 0 ) ;

May omit schema


insert into student
values (1897 , ‘ ‘ABC ’ ’ , 7 , 0 . 0 ) ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 36 / 52


Insertion

insert into . . . values statement


Example: Create a new student “ABC” with roll 1897 and
department 7
i n s e r t i n t o s t u d e n t ( r o l l , name , dept , c p i )
values (1897 , ‘ ‘ABC ’ ’ , 7 , 0 . 0 ) ;

May omit schema


insert into student
values (1897 , ‘ ‘ABC ’ ’ , 7 , 0 . 0 ) ;

If value is not known, specify null


insert into student
values (1897 , ‘ ‘ABC ’ ’ , 7 , n u l l ) ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 36 / 52


Insertion

insert into . . . values statement


Example: Create a new student “ABC” with roll 1897 and
department 7
i n s e r t i n t o s t u d e n t ( r o l l , name , dept , c p i )
values (1897 , ‘ ‘ABC ’ ’ , 7 , 0 . 0 ) ;

May omit schema


insert into student
values (1897 , ‘ ‘ABC ’ ’ , 7 , 0 . 0 ) ;

If value is not known, specify null


insert into student
values (1897 , ‘ ‘ABC ’ ’ , 7 , n u l l ) ;

To avoid null, specify schema


i n s e r t i n t o s t u d e n t ( r o l l , name , dept )
values (1897 , ‘ ‘ABC ’ ’ , 7 ) ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 36 / 52


Insertion (contd.)

Example: Create a course of code 9 for every department with the


same type

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 37 / 52


Insertion (contd.)

Example: Create a course of code 9 for every department with the


same type
i n s e r t i n t o course ( code , t i t l e , webpage , c t y p e )
s e l e c t 9 , ‘ ‘ New ’ ’ , n u l l , type
from course
where type i n (
select deptid
from department ) ;

Query is evaluated fully before any tuple is inserted

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 37 / 52


Insertion (contd.)

Example: Create a course of code 9 for every department with the


same type
i n s e r t i n t o course ( code , t i t l e , webpage , c t y p e )
s e l e c t 9 , ‘ ‘ New ’ ’ , n u l l , type
from course
where type i n (
select deptid
from department ) ;

Query is evaluated fully before any tuple is inserted


Otherwise, infinite insertion happens for queries like
insert into r
s e l e c t * from r ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 37 / 52


Deletion

delete from . . . where statement

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 38 / 52


Deletion

delete from . . . where statement


Example: Delete student with roll number 1946

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 38 / 52


Deletion

delete from . . . where statement


Example: Delete student with roll number 1946
d e l e t e from s t u d e n t
where r o l l = 1946;

where selects tuples that will be deleted

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 38 / 52


Deletion

delete from . . . where statement


Example: Delete student with roll number 1946
d e l e t e from s t u d e n t
where r o l l = 1946;

where selects tuples that will be deleted


If where is empty,

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 38 / 52


Deletion

delete from . . . where statement


Example: Delete student with roll number 1946
d e l e t e from s t u d e n t
where r o l l = 1946;

where selects tuples that will be deleted


If where is empty, all tuples are deleted

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 38 / 52


Deletion

delete from . . . where statement


Example: Delete student with roll number 1946
d e l e t e from s t u d e n t
where r o l l = 1946;

where selects tuples that will be deleted


If where is empty, all tuples are deleted
Delete all students
d e l e t e from s t u d e n t ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 38 / 52


Deletion (contd.)

Example: Delete all students whose CPI is less than the average
CPI

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 39 / 52


Deletion (contd.)

Example: Delete all students whose CPI is less than the average
CPI
d e l e t e from s t u d e n t
where c p i < (
s e l e c t avg ( c p i )
from s t u d e n t ) ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 39 / 52


Deletion (contd.)

Example: Delete all students whose CPI is less than the average
CPI
d e l e t e from s t u d e n t
where c p i < (
s e l e c t avg ( c p i )
from s t u d e n t ) ;

Average is computed before any tuple is deleted


It is not re-computed

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 39 / 52


Deletion (contd.)

Example: Delete all students whose CPI is less than the average
CPI
d e l e t e from s t u d e n t
where c p i < (
s e l e c t avg ( c p i )
from s t u d e n t ) ;

Average is computed before any tuple is deleted


It is not re-computed
Otherwise, average keeps changing
Ultimately, only the student with the largest CPI remains

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 39 / 52


Updating
update . . . set . . . where statement
where selects tuples that will be updated

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 40 / 52


Updating
update . . . set . . . where statement
where selects tuples that will be updated
Example: Update value of grade ‘E’ to 2

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 40 / 52


Updating
update . . . set . . . where statement
where selects tuples that will be updated
Example: Update value of grade ‘E’ to 2
update grade
set value = 2 . 0
where gradecode = ‘E ’ ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 40 / 52


Updating
update . . . set . . . where statement
where selects tuples that will be updated
Example: Update value of grade ‘E’ to 2
update grade
set value = 2 . 0
where gradecode = ‘E ’ ;

If where is empty, all tuples are updated with the new value
Example: Increase CPI of all students by 5%

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 40 / 52


Updating
update . . . set . . . where statement
where selects tuples that will be updated
Example: Update value of grade ‘E’ to 2
update grade
set value = 2 . 0
where gradecode = ‘E ’ ;

If where is empty, all tuples are updated with the new value
Example: Increase CPI of all students by 5%
update s t u d e n t
set c p i = c p i * 1 . 0 5 ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 40 / 52


Updating (contd.)
Example: Increase CPI of all students by 10% where CPI is less
than 6.0 and by 5% otherwise
update s t u d e n t set c p i = c p i * 1.05 where c p i >= 6 . 0 ;
update s t u d e n t set c p i = c p i * 1.10 where c p i < 6 . 0 ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 41 / 52


Updating (contd.)
Example: Increase CPI of all students by 10% where CPI is less
than 6.0 and by 5% otherwise
update s t u d e n t set c p i = c p i * 1.05 where c p i >= 6 . 0 ;
update s t u d e n t set c p i = c p i * 1.10 where c p i < 6 . 0 ;

Order of statements is important

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 41 / 52


Updating (contd.)
Example: Increase CPI of all students by 10% where CPI is less
than 6.0 and by 5% otherwise
update s t u d e n t set c p i = c p i * 1.05 where c p i >= 6 . 0 ;
update s t u d e n t set c p i = c p i * 1.10 where c p i < 6 . 0 ;

Order of statements is important


case statement handles conditional updates in a better manner
and is sometimes necessary

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 41 / 52


Updating (contd.)
Example: Increase CPI of all students by 10% where CPI is less
than 6.0 and by 5% otherwise
update s t u d e n t set c p i = c p i * 1.05 where c p i >= 6 . 0 ;
update s t u d e n t set c p i = c p i * 1.10 where c p i < 6 . 0 ;

Order of statements is important


case statement handles conditional updates in a better manner
and is sometimes necessary
Example: Increase CPI of all students by 10% where CPI is less
than 6.0, by 5% when less than 8.0, and 2% otherwise

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 41 / 52


Updating (contd.)
Example: Increase CPI of all students by 10% where CPI is less
than 6.0 and by 5% otherwise
update s t u d e n t set c p i = c p i * 1.05 where c p i >= 6 . 0 ;
update s t u d e n t set c p i = c p i * 1.10 where c p i < 6 . 0 ;

Order of statements is important


case statement handles conditional updates in a better manner
and is sometimes necessary
Example: Increase CPI of all students by 10% where CPI is less
than 6.0, by 5% when less than 8.0, and 2% otherwise
update s t u d e n t
set c p i =
case ( c p i )
when c p i < 6 . 0 then c p i * 1.10
when c p i < 8 . 0 then c p i * 1.05
else c p i * 1.02
end ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 41 / 52


Join

Join types: inner join, left (outer) join, right (outer) join, full (outer)
join
Join conditions: natural, on ⟨ predicate ⟩, using (⟨ attribute list ⟩)
Examples
s t u d e n t inner j o i n program on s t u d e n t . r o l l = program . r o l l ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 42 / 52


Join

Join types: inner join, left (outer) join, right (outer) join, full (outer)
join
Join conditions: natural, on ⟨ predicate ⟩, using (⟨ attribute list ⟩)
Examples
s t u d e n t inner j o i n program on s t u d e n t . r o l l = program . r o l l ;
s t u d e n t n a t u r a l l e f t j o i n program ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 42 / 52


Join

Join types: inner join, left (outer) join, right (outer) join, full (outer)
join
Join conditions: natural, on ⟨ predicate ⟩, using (⟨ attribute list ⟩)
Examples
s t u d e n t inner j o i n program on s t u d e n t . r o l l = program . r o l l ;
s t u d e n t n a t u r a l l e f t j o i n program ;
s t u d e n t r i g h t outer j o i n program using ( r o l l ) ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 42 / 52


Join

Join types: inner join, left (outer) join, right (outer) join, full (outer)
join
Join conditions: natural, on ⟨ predicate ⟩, using (⟨ attribute list ⟩)
Examples
s t u d e n t inner j o i n program on s t u d e n t . r o l l = program . r o l l ;
s t u d e n t n a t u r a l l e f t j o i n program ;
s t u d e n t r i g h t outer j o i n program using ( r o l l ) ;

Inner natural join is assumed when nothing is mentioned

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 42 / 52


Join

Join types: inner join, left (outer) join, right (outer) join, full (outer)
join
Join conditions: natural, on ⟨ predicate ⟩, using (⟨ attribute list ⟩)
Examples
s t u d e n t inner j o i n program on s t u d e n t . r o l l = program . r o l l ;
s t u d e n t n a t u r a l l e f t j o i n program ;
s t u d e n t r i g h t outer j o i n program using ( r o l l ) ;

Inner natural join is assumed when nothing is mentioned


Multiple relations can be joined
s t u d e n t j o i n program j o i n r e g i s t r a t i o n ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 42 / 52


Views
A relation that is not present physically but is made visible to the
user is called a view
A view is a virtual relation derived from other relations

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 43 / 52


Views
A relation that is not present physically but is made visible to the
user is called a view
A view is a virtual relation derived from other relations
It helps in query processing
If a sub-query is very common, obtain a view for it
It helps in hiding certain data from a user
A view can leave out sensitive attributes
Example:
create view s t u d e n t p r o g r a m as
s t u d e n t n a t u r a l j o i n program ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 43 / 52


Views
A relation that is not present physically but is made visible to the
user is called a view
A view is a virtual relation derived from other relations
It helps in query processing
If a sub-query is very common, obtain a view for it
It helps in hiding certain data from a user
A view can leave out sensitive attributes
Example:
create view s t u d e n t p r o g r a m as
s t u d e n t n a t u r a l j o i n program ;

A view can be deleted simply using drop


drop s t u d e n t p r o g r a m ;

A view has full query capabilities, but limited modification facilities


A view can be defined using other views, but not itself
Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 43 / 52
Storing Views
A view is not stored physically
Only the query expression is stored
Wherever a view is used, the query expression is substituted

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 44 / 52


Storing Views
A view is not stored physically
Only the query expression is stored
Wherever a view is used, the query expression is substituted
Example: Find students and corresponding programs for “CSE”

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 44 / 52


Storing Views
A view is not stored physically
Only the query expression is stored
Wherever a view is used, the query expression is substituted
Example: Find students and corresponding programs for “CSE”
select *
from s t u d e n t p r o g r a m
where dept = ‘ ‘CSE ’ ’ ;

is expanded at runtime to

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 44 / 52


Storing Views
A view is not stored physically
Only the query expression is stored
Wherever a view is used, the query expression is substituted
Example: Find students and corresponding programs for “CSE”
select *
from s t u d e n t p r o g r a m
where dept = ‘ ‘CSE ’ ’ ;

is expanded at runtime to
select *
from
( s t u d e n t n a t u r a l j o i n program )
where dept = ‘ ‘CSE ’ ’ ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 44 / 52


Storing Views
A view is not stored physically
Only the query expression is stored
Wherever a view is used, the query expression is substituted
Example: Find students and corresponding programs for “CSE”
select *
from s t u d e n t p r o g r a m
where dept = ‘ ‘CSE ’ ’ ;

is expanded at runtime to
select *
from
( s t u d e n t n a t u r a l j o i n program )
where dept = ‘ ‘CSE ’ ’ ;

This allows to capture all updates in the base relations

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 44 / 52


Storing Views
A view is not stored physically
Only the query expression is stored
Wherever a view is used, the query expression is substituted
Example: Find students and corresponding programs for “CSE”
select *
from s t u d e n t p r o g r a m
where dept = ‘ ‘CSE ’ ’ ;

is expanded at runtime to
select *
from
( s t u d e n t n a t u r a l j o i n program )
where dept = ‘ ‘CSE ’ ’ ;

This allows to capture all updates in the base relations


If a view is materialized, it is stored physically
To ensure consistency, database must update materialized views
once base relations are updated
Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 44 / 52
Updating a View
Updating a view causes many problems, and is, in general, not
allowed

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 45 / 52


Updating a View
Updating a view causes many problems, and is, in general, not
allowed
Update must map to updates on the base relations

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 45 / 52


Updating a View
Updating a view causes many problems, and is, in general, not
allowed
Update must map to updates on the base relations
If a view involves join or Cartesian product, update must map to
updates on all the base relations

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 45 / 52


Updating a View
Updating a view causes many problems, and is, in general, not
allowed
Update must map to updates on the base relations
If a view involves join or Cartesian product, update must map to
updates on all the base relations
Not always possible

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 45 / 52


Updating a View
Updating a view causes many problems, and is, in general, not
allowed
Update must map to updates on the base relations
If a view involves join or Cartesian product, update must map to
updates on all the base relations
Not always possible
Problems with insert or delete

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 45 / 52


Updating a View
Updating a view causes many problems, and is, in general, not
allowed
Update must map to updates on the base relations
If a view involves join or Cartesian product, update must map to
updates on all the base relations
Not always possible
Problems with insert or delete
Spurious tuple
Null
Non-uniqueness

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 45 / 52


Triggers

A trigger statement allows automatic and active management


during database modifications
It is invoked only by the database engine and not by the user

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 46 / 52


Triggers

A trigger statement allows automatic and active management


during database modifications
It is invoked only by the database engine and not by the user
It follows the event-condition-action (ECA) model
Event: Database modification
Condition: Invoked only if true; if no condition, then assumed true
Action: Database action or any program

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 46 / 52


Triggers

A trigger statement allows automatic and active management


during database modifications
It is invoked only by the database engine and not by the user
It follows the event-condition-action (ECA) model
Event: Database modification
Condition: Invoked only if true; if no condition, then assumed true
Action: Database action or any program
It may not allow the full range of modification statements

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 46 / 52


Triggers

A trigger statement allows automatic and active management


during database modifications
It is invoked only by the database engine and not by the user
It follows the event-condition-action (ECA) model
Event: Database modification
Condition: Invoked only if true; if no condition, then assumed true
Action: Database action or any program
It may not allow the full range of modification statements
It can be called before or after the modification
New and old values are referenced using new and old keywords
new refers to a inserted or new value of updated tuple
old refers to a deleted or old value of updated tuple
By default, it is for each row (i.e., tuple)

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 46 / 52


Creating Triggers

Created using a create trigger command

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 47 / 52


Creating Triggers

Created using a create trigger command


Example: Update the coursecode of offering when the code of a
course of type 9 is updated

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 47 / 52


Creating Triggers

Created using a create trigger command


Example: Update the coursecode of offering when the code of a
course of type 9 is updated
create t r i g g e r update code
a f t e r update of code on course
f o r each row
when c t y p e = 9
begin
update o f f e r i n g set coursecode = new . code where
coursecode = o l d . code ;
end ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 47 / 52


Creating Triggers

Created using a create trigger command


Example: Update the coursecode of offering when the code of a
course of type 9 is updated
create t r i g g e r update code
a f t e r update of code on course
f o r each row
when c t y p e = 9
begin
update o f f e r i n g set coursecode = new . code where
coursecode = o l d . code ;
end ;

A trigger can be deleted simply using drop


drop update code ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 47 / 52


Indices in SQL
create [unique] index name on r (a, b) creates an index name on
attributes a, b of relation r
unique does not allow duplicates on the atrributes
create index i d x c t y p e on course ( c t y p e ) ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 48 / 52


Indices in SQL
create [unique] index name on r (a, b) creates an index name on
attributes a, b of relation r
unique does not allow duplicates on the atrributes
create index i d x c t y p e on course ( c t y p e ) ;

Index will be used whenever attribute a of relation r is used


Often, primary keys are implicity indexed

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 48 / 52


Indices in SQL
create [unique] index name on r (a, b) creates an index name on
attributes a, b of relation r
unique does not allow duplicates on the atrributes
create index i d x c t y p e on course ( c t y p e ) ;

Index will be used whenever attribute a of relation r is used


Often, primary keys are implicity indexed
Slows down modification operations as index is also modified

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 48 / 52


Indices in SQL
create [unique] index name on r (a, b) creates an index name on
attributes a, b of relation r
unique does not allow duplicates on the atrributes
create index i d x c t y p e on course ( c t y p e ) ;

Index will be used whenever attribute a of relation r is used


Often, primary keys are implicity indexed
Slows down modification operations as index is also modified
drop index i deletes the index
drop index i d x c t y p e ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 48 / 52


Access Control
SQL is a data control language (DCL)
Can be used to control accesses of users to data
Data security

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 49 / 52


Access Control
SQL is a data control language (DCL)
Can be used to control accesses of users to data
Data security
grant: grant privilege on object to user [with grant option]
privilege: Can be all or specific:
System privileges on tables and views: create, alter, drop
Object privileges: select, insert/update/delete, execute
object: table, view, stored procedure
user: public or particular username or role
with grant option: can grant access rights to others

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 49 / 52


Access Control
SQL is a data control language (DCL)
Can be used to control accesses of users to data
Data security
grant: grant privilege on object to user [with grant option]
privilege: Can be all or specific:
System privileges on tables and views: create, alter, drop
Object privileges: select, insert/update/delete, execute
object: table, view, stored procedure
user: public or particular username or role
with grant option: can grant access rights to others
revoke: revoke privilege on object from user

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 49 / 52


Access Control
SQL is a data control language (DCL)
Can be used to control accesses of users to data
Data security
grant: grant privilege on object to user [with grant option]
privilege: Can be all or specific:
System privileges on tables and views: create, alter, drop
Object privileges: select, insert/update/delete, execute
object: table, view, stored procedure
user: public or particular username or role
with grant option: can grant access rights to others
revoke: revoke privilege on object from user
grant s e l e c t on s t u d e n t to xyz ;
grant a l l on course to abc with grant option ;
revoke create on s t u d e n t from xyz ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 49 / 52


Transaction Control
Transactions are groups of statements that are executed
atomically

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 50 / 52


Transaction Control
Transactions are groups of statements that are executed
atomically
set transaction [read write | read only] starts a transaction

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 50 / 52


Transaction Control
Transactions are groups of statements that are executed
atomically
set transaction [read write | read only] starts a transaction
After modification operations, a transaction can commit or rollback

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 50 / 52


Transaction Control
Transactions are groups of statements that are executed
atomically
set transaction [read write | read only] starts a transaction
After modification operations, a transaction can commit or rollback
Within a transaction, a checkpoint can be set by savepoint
savepoint-name

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 50 / 52


Transaction Control
Transactions are groups of statements that are executed
atomically
set transaction [read write | read only] starts a transaction
After modification operations, a transaction can commit or rollback
Within a transaction, a checkpoint can be set by savepoint
savepoint-name
A transaction can rollback to a particular savepoint-name

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 50 / 52


Transaction Control
Transactions are groups of statements that are executed
atomically
set transaction [read write | read only] starts a transaction
After modification operations, a transaction can commit or rollback
Within a transaction, a checkpoint can be set by savepoint
savepoint-name
A transaction can rollback to a particular savepoint-name
A savepoint can be removed by release savepoint savepoint-name

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 50 / 52


Transaction Control
Transactions are groups of statements that are executed
atomically
set transaction [read write | read only] starts a transaction
After modification operations, a transaction can commit or rollback
Within a transaction, a checkpoint can be set by savepoint
savepoint-name
A transaction can rollback to a particular savepoint-name
A savepoint can be removed by release savepoint savepoint-name
roll name
1 AB
2 CD
set t r a n s a c t i o n read w r i t e ;
d e l e t e from s t u d e n t where r o l l = 1 ;
commit ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 50 / 52


Transaction Control
Transactions are groups of statements that are executed
atomically
set transaction [read write | read only] starts a transaction
After modification operations, a transaction can commit or rollback
Within a transaction, a checkpoint can be set by savepoint
savepoint-name
A transaction can rollback to a particular savepoint-name
A savepoint can be removed by release savepoint savepoint-name
roll name
1 AB
2 CD
set t r a n s a c t i o n read w r i t e ;
d e l e t e from s t u d e n t where r o l l = 1 ;
commit ;

roll name
2 CD
Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 50 / 52
Savepoint Example
roll name
1 AB
2 CD
3 EF
4 GH

set t r a ns a c t i o n read w r i t e ;
savepoint sp1 ;
d e l e t e from s t u d e n t where r o l l = 1 ;
savepoint sp2 ;
d e l e t e from s t u d e n t where r o l l = 2 ;
r o l l b a c k to sp2 ;

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 51 / 52


Savepoint Example
roll name
1 AB
2 CD
3 EF
4 GH

set t r a ns a c t i o n read w r i t e ;
savepoint sp1 ;
d e l e t e from s t u d e n t where r o l l = 1 ;
savepoint sp2 ;
d e l e t e from s t u d e n t where r o l l = 2 ;
r o l l b a c k to sp2 ;

roll name
2 CD
3 EF
4 GH

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 51 / 52


Variants in SQL
SQL standards have evolved a lot over the years
Different vendors provide different flavors and may not implement
every feature

Arnab Bhattacharya ([email protected]) CS315: SQL 2024-25 52 / 52

You might also like