Presentation is loading. Please wait.

Presentation is loading. Please wait.

Greg Riccardi Florida State University. Using SQL to Manipulate Database Content and Structure How to create queries in SQL –Simple select statements.

Similar presentations


Presentation on theme: "Greg Riccardi Florida State University. Using SQL to Manipulate Database Content and Structure How to create queries in SQL –Simple select statements."— Presentation transcript:

1 Greg Riccardi Florida State University

2 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

3 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

4 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

5 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’

6 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

7 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 145-09-0967UnoJane145-09-096701/14/20028:153no12:00 145-09-0967UnoJane145-09-096701/16/20028:153no12:00 245-11-4554ToulouseJie245-11-455401/14/20028:153no12:00 376-77-0099ThreatAyisha376-77-009902/23/200214:005no22:00 376-77-0099ThreatAyisha376-77-009903/21/200214:005no22:00 376-77-0099ThreatAyisha376-77-009902/23/200214:005no22:00 376-77-0099ThreatAyisha376-77-009901/03/200210:005no14:00 376-77-0099ThreatAyisha376-77-009901/03/200215:005no19:00 479-98-0098FortuneJulian 579-98-8778FivozinskyBruce

8 Outer join queries in Access Join properties dialog Left join symbol Left join option

9 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

10 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

11 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

12 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

13 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

14 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

15 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)

16 Nested select in Access nested select statement in text false for not exists

17 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

18 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)

19 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

20 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 = ’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)

21 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)

22 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

23 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)

24 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))

25 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 )

26 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)

27 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

28 SQL statements for bighit online video sales See Web site for examples


Download ppt "Greg Riccardi Florida State University. Using SQL to Manipulate Database Content and Structure How to create queries in SQL –Simple select statements."

Similar presentations


Ads by Google