Greg Riccardi
Florida State University
Using SQL to Manipulate Database Content and Structure
• How to create queries in SQL – Simple select statements – Simple join queries– Outer join queries– Queries with multiple relational operators– String pattern matching and ordering results– Expressions, literals, and aggregates – Group by and having clauses– Nested select statements– Set operations
• How to Modify database content with SQL – Insert statements– Update statements– Delete statements
• How to Create and manipulate table definitions with SQL– Creating tables and defining attributes – Key and foreign key constraint specifications– Default values, nulls, and constraints– Adding, removing, and modifying attributes– Schemas and user ids – Drop statements
• SQL statements for bighit online video sales
How to create queries in SQL
• SQL is a language with– Syntax: the form of statements– Semantics: the meaning of statements
• This chapter demonstrates syntax– Examples of all types of statements– Shows how each query of Chapter 8 is represented in SQL– Shows additional SQL capabilities
• This chapter demonstrates semantics– Relates SQL statements to result tables– Shows what each statement means
Simple select statements
• Select statement in SQL combines many relational operations– select <attribute names> from <tables> where <condition>
• select clause – specifies the attributes that go in the results table.
• from clause – specifies the source tables that the database will access in order
to execute the query.
• where clause – specifies the selection conditions, including the join condition
Examples of Simple Select Statements
• Examples– Project Customer on lastName, firstName with duplicates
• select lastName, firstName from Customer – Project Customer on lastName, firstName without duplicates
• select distinct lastName, firstName from Customer– select from Customer where lastName = ‘Doe’
• select * from Customer where lastName = 'Doe'
• Notice the use of string literals with single quotes– ‘Doe’
Simple join queries
• Example join operation– join Employee and TimeCard where Employee.ssn =
TimeCard.ssn
• Two forms of join– select * from Employee, TimeCard
where Employee.ssn = TimeCard.ssn– select * from Employee join TimeCard
on Employee.ssn = TimeCard.ssn
Outer Joins• Outer joins add rows that have no match
– Left join adds all rows from left input table that do not match any row of right table
– select * from Employee left outer join TimeCard on Employee.ssn = TimeCard.ssn
Employee.Ssn lastName FirstName TimeCard.ssn date startTime storeId paid End Time
145-09-0967 Uno Jane 145-09-0967 01/14/2002 8:15 3 no 12:00
145-09-0967 Uno Jane 145-09-0967 01/16/2002 8:15 3 no 12:00
245-11-4554 Toulouse Jie 245-11-4554 01/14/2002 8:15 3 no 12:00
376-77-0099 Threat Ayisha 376-77-0099 02/23/2002 14:00 5 no 22:00
376-77-0099 Threat Ayisha 376-77-0099 03/21/2002 14:00 5 no 22:00
376-77-0099 Threat Ayisha 376-77-0099 02/23/2002 14:00 5 no 22:00
376-77-0099 Threat Ayisha 376-77-0099 01/03/2002 10:00 5 no 14:00
376-77-0099 Threat Ayisha 376-77-0099 01/03/2002 15:00 5 no 19:00
479-98-0098 Fortune Julian
579-98-8778 Fivozinsky Bruce
Outer join queries in Access
Join propertiesdialog
Left join symbol Left join option
Queries with multiple relational operators
• Example of SQL statement with 3 joins, projection and selection
• select lastName, firstName, title, dateRented Projectionfrom Movie, Video, PreviousRental, Customer Source tableswhere Movie.movieId = Video.movieId Join conditionand Customer.accountId = PreviousRental.accountId Join conditionand Video.videoId = PreviousRental.videoId Join conditionand dateRented > '2001-dec-1' Selection condition
• Single SQL statement combines many operations
String pattern matching and ordering results
• Pattern matching in where clause– select * from Movie where title like '%alligator%'
– select * from Movie where title not like 'The %'
– select * from Employee where ssn like '___-44-____‘
• Ordering results in SQL– select * from Customer order by lastName, firstName
– select * from Customer order by accountId desc
– select * from Customer order by lastName desc, zipcode asc
• Ordering is part of SQL– Relational model declares table rows are unordered
– SQL and Access treat tables as lists of rows in some order
• Unordered queries return a list of rows in no particular order– The server can produce rows in any order
– Generally produces rows in the order that is easiest or fastest to create
Expressions, literals, and aggregates
• Expressions and literals in select clause– select lastName, firstName, Employee.ssn, date,
(endTime-startTime)*24 as hoursWorkedfrom Employee, TimeCard where Employee.ssn = TimeCard.ssn
• Creates a table with 5 attributes• 5th attribute of an output row is calculated from the endTime
and startTime attributes of the input row– Select lastName, ‘George’ from Emplyee
• Creates a 2 attribute table with all employees’ last names as first attribute, and literal ‘George’ as second attribute
• Aggregates: putting many input rows into 1 output row– select count(*) from Rental where accountId = 101 – select count(distinct lastName) from Customer
Aggregating with group by
• Group by is used to – divide input rows into groups and
– Produce one output row per group
– select videoId, avg(cost) as averageCost, sum(cost) as totalCost, count(*) as numRentalsfrom PreviousRental group by videoId
videoId averageCost totalCost numRentals
101 $2.49 $4.98 2
112 $1.99 $1.99 1
113 $2.49 $7.47 3
77564 $3.35 $3.35 1
99787 $3.95 $3.95 1
Having clause to restrict outputs
• Having clause selects groups to produce output rows– A group produces an output row only if having condition is true– select title, genre, count(*) as numRentals,
avg(cost) as average, sum(cost) as sumfrom Movie, Video, PreviousRentalwhere Movie.movieId = Video.movieId
and Video.videoId = PreviousRental.videoIdgroup by Movie.movieId, title, genrehaving count(*)>1
• A group with count(*) [number of rows in group] <=1 does not produce an output row
Title Genre numRentals average sum
Annie Hall comedy 4 $2.37 $9.46
The Thirty-nine Steps mystery 2 $2.49 $4.98
Group by and having in access
having count(*)>1group by title
average: avg(cost)
sum: sum(cost)
group by movieIddon’t show movieId
Total row
numRentals: count(*)
group by genre
Nested select statements
• More complex SQL queries may be easier to understand if divided– select * from Customer where accountId in
(select accountId from PreviousRental where dateRented >=’dec/1/2001’ and
dateRented<’1/1/2002’)))– select * from Customer C where not exists
(select * from PreviousRental Pwhere C.accountId = P.accountId)
Nested select in Access
nested select statement in text
false for not exists
Set operations
• Set operations in SQL with union• Union operation: rentals and previous rentals with marker
attribute– (select *, ’Rental’ as sourceTable from Rental)
union (select *, ’PreviousRental’ as sourceTable from PreviousRental)
• Partial result table
accountId videoId dateRented dateDue cost sourceTable
103 101 1/ 3/ 99 1/ 4/ 99 $1.59 Rental
101 113 2/ 22/ 99 2/ 25/ 99 $3.00 Rental
101 114 2/ 22/ 99 2/ 25/ 99 $3.00 Rental
101 101 12/ 9/ 98 12/ 10/ 98 $2.49 PreviousRental
101 112 1/ 13/ 98 1/ 4/ 98 $1.99 PreviousRental
101 113 1/ 15/ 99 1/ 15/ 99 $0.99 PreviousRental
201 77564 1/ 14/ 99 1/ 24/ 99 $3.35 PreviousRental
Rows from Rental
Rows from PreviousRental
Marker attribute
Set operations
• Set operations in SQL with intersect and except• Intersection operation: videotapes that are rented now,
but not for the first time– (select videoId from Rental)
intersect (select videoId from PreviousRental)
• Difference operation: videotapes that currently rented for the first time, and those that have been rented but are not currently rented– (select videoId from Rental)
except (select videoId from PreviousRental)
– (select videoId from PreviousRental)except(select videoId from Rental)
How to Modify database content with SQL
• Modify content with insert statements– insert into Customer values (555, 'Yu', 'Jia','540 Magnolia Hall',
'Tallahassee', 'FL', '32306', 0.00)– insert into Customer (firstName, lastName, accountId)
values ('Jia', 'Yu', 555)• Insert from select statement
– insert into <table> <select statement>• Fields of select must match fields of insert in order and type
– insert into PayStatement(ssn, hourlyRate, numHours, amountPaid, datePaid)
select TimeCard.ssn, hourlyRate, sum((endTime-startTime)*24),sum((endTime-startTime)*24*hourlyRate),today
from TimeCard, HourlyEmployeewhere TimeCard.ssn=HourlyEmployee.ssn and paid = false group by TimeCard.ssn, hourlyRate
Update statements
• General form of update statement– update <table> set <attribute>=<value> ...
where <selection condition>
• Update to mark every timecard as paid– update TimeCard set paid = true where paid = false
• Update to give every hourly employee a 10% raise– update HourlyEmployee set hourlyRate = hourlyRate * 1.1
where ssn = ’145-09-0967’
• Update to give every hourly employee a raise of 10% of the average hourly rate: every gets same amount– update HourlyEmployee set hourlyRate = hourlyRate + 0.10 *
(select avg(hourlyRate) from HourlyEmployee)
Delete statements
• Each delete statement deletes from one table according to some selection clause
• Delete every row from table– delete from Employee
• Delete all time cards that have no corresponding hourly employee– delete from Timecard
where not exists (select * from HourlyEmployee where TimeCard.ssn = HourlyEmployee.ssn)
How to Create and manipulate table definitions with SQL
• A create table statement specifies a table name and a list of attributes and constraints for a new table
• Example with no contraints– create table Customer (accountId int, lastName varchar(32), firstName
varchar(32), street varchar(100), city varchar(32), state char(2), zipcode varchar(9), balance real)
• Some example attribute types
Integer integer, int, smallint, long
Floating point float, real, double precision
Numeric types
Formatted decimal(i,j), dec(i,j)
Fixed length char(n), character(n) Character-string types
Varying length varchar(n), char varying(n), character varying(n)
Fixed length bit(n) Bit-string types
Varying length bit varying(n)
Date and time types date, time, datetime, timestamp, time with time zone, interval
Large text types Character long varchar(n), text, clob
How to Create and manipulate table definitions with SQL
• A create table statement specifies a table name and a list of attributes and constraints for a new table
• Example with no contraints– create table Customer (accountId int, lastName varchar(32),
firstName varchar(32), street varchar(100), city varchar(32), state char(2), zipcode varchar(9), balance real)
• Add a primary key constraint– create table Customer (accountId int primary key, lastName
varchar(32), firstName varchar(32), street varchar(100), city varchar(32), state char(2), zipcode varchar(9), balance real)
Creating tables and defining attributes
• Add primary key constraint as separate clause– create table Store (storeId int, street varchar(100), city
varchar(32), state char(2), zipcode varchar(9), primary key storeId, manager int references Employee)
• Add primary key constraint as characteristic of attribute– create table Movie (movieId varchar(10) primary key, title
varchar(100) unique, genre varchar(32), rating varchar(5), accountId int)
• Add foreign key constraints– create table Rental (accountId int, videoId varchar(10) unique,
dateRented datetime, dateDue datetime, cost real, primary key (accountId, videoId), foreign key (accountId)references Customer(accountId) foreign key (videoId)references Video(videoId))
Default values, nulls, and constraints
• Creating a table with non-null constraints and default values– create table Video (
videoId varchar(10) primary key,movieId varchar(10) not null references Movie,storeId int references Store default 1
)
Adding, removing, and modifying attributes
• An alter table statement change the definition of a table• Add an attribute with a value
– alter table Video add (dateAcquired date = Today)
• Modify and drop table constraints and drop an attribute– alter table Video
modify (storeId not null)drop constraint (primary key videoId) drop (movieId)
Drop statements
• Drop a table: completely destroys table and all contents– drop table Employee
• What happens when table contains keys and foreign keys
• Cascade characteristic tells server to delete all rows of other tables that have foreign keys to the dropped table– drop table Employee cascade
• Restrict characteristic tells server to block the delete operation if additional rows would have to be deleted– drop table Employee restrict
SQL statements for bighit online video sales
• See Web site for examples