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 from where 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.SsnlastNameFirstNameTimeCard.ssndatestartTimestoreIdpaidEnd Time UnoJane /14/20028:153no12: UnoJane /16/20028:153no12: ToulouseJie /14/20028:153no12: ThreatAyisha /23/200214:005no22: ThreatAyisha /21/200214:005no22: ThreatAyisha /23/200214:005no22: ThreatAyisha /03/200210:005no14: ThreatAyisha /03/200215:005no19: FortuneJulian FivozinskyBruce
Outer join queries in Access Join properties dialog 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, dateRentedProjection from Movie, Video, PreviousRental, CustomerSource tables where Movie.movieId = Video.movieId Join condition and Customer.accountId = PreviousRental.accountId Join condition and Video.videoId = PreviousRental.videoIdJoin condition and 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 hoursWorked from Employee, TimeCard where Employee.ssn = TimeCard.ssn Creates a table with 5 attributes 5 th 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 numRentals from PreviousRental group by videoId
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 sum from Movie, Video, PreviousRental where Movie.movieId = Video.movieId and Video.videoId = PreviousRental.videoId group by Movie.movieId, title, genre having count(*)>1 A group with count(*) [number of rows in group] <=1 does not produce an output row
Group by and having in access having count(*)>1 group by title average: avg(cost) sum: sum(cost) group by movieId don’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 P where 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 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 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, HourlyEmployee where TimeCard.ssn=HourlyEmployee.ssn and paid = false group by TimeCard.ssn, hourlyRate
Update statements General form of update statement –update set =... where 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 = ’ ’ Update to give every hourly employee a raise of 10% of the average hourly rate: every gets same amount –update HourlyEmployee set hourlyRate = hourlyRate * (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
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