Presentation is loading. Please wait.

Presentation is loading. Please wait.

Database SQL.

Similar presentations


Presentation on theme: "Database SQL."— Presentation transcript:

1 Database SQL

2 Relational language SQL
SQL or Structured Query Language SQL is an interactive Query language and database programming Language

3 SQL History Originally (mid-’70s) defined as Sequel in System R project at IBM San Jose Research Center Name change to SQL, multiple iterations of standards (’86, ’87, ’89, ’92,…) Has usual good and bad aspects of much-used, much-extended languages Think of C++ or Fortran-90…

4 SQL From American National Institue ANSI, it was SQL-86 (ANSI 1986) and SQL-2 (SQL-92) SQL Language is divided into DDL : Data Definition Language DML : Data Manipulation Language DCL : Data Control Language

5 DDL It is commands used for: DDL commands are CREATE ALTER DROP
Creates databases, tables, indices Create views Specify integrity constraints DDL commands are CREATE ALTER DROP

6 DML For values in the database DML commands: SELECT UPDATE DELETE
Perform queries Perform updates DML commands: SELECT UPDATE DELETE INSERT

7 DCL For controlling the access of data DCL commands are GRANT REVOKE

8 SQL - DDL It used to define and manage the structure of tables in the database Its statements as CREATE TABLE CREATE INDEX ALTER TABLE DROP TABLE DROP INDEX

9 Creating tables create table name (attr1 domain1, attr2 domain2, …)
Can also have integrity constraints not null unique primary key (attr1, attr2, …) check (predicate) To be a primary key, must be non-null and unique Different SQLs differ about whether not null is implied by primary key

10 CREATE Commands Create the table S (s#, Sname, Status, City)
CREATE TABLE S (s# CHAR(5), Sname CHAR(20), Status INT, City CHAR(15), PRIMARY KEY (s#)).

11 Data Definition Language
Every attribute has a domain Some common ones: char(n): character string of fixed length n varchar(n): character string of length up to n int: integer, exact size machine-dependent smallint: another (usually smaller than int) integer

12 More common domains numeric(p,d): fixed point number with p total digits, d of them to the right of the decimal point real, double precision: floating-point numbers float(n): floating-point with precision at least n date: a calendar date (day, month, year) time: hours, minutes, seconds datetime: a time on a date

13 Example: Default Values
CREATE TABLE Students( name CHAR(30) PRIMARY KEY, addr CHAR(50) DEFAULT ‘123 Sesame St.’, phone CHAR(16) );

14 Other Keys CREATE TABLE Product ( productID CHAR(10), name CHAR(30),
category VARCHAR(20), price INT, PRIMARY KEY (productID), UNIQUE (name, category)) There is at most one PRIMARY KEY; there can be many UNIQUE

15 Foreign Key Constraints
(name, category) must be a PRIMARY KEY CREATE TABLE Purchase ( prodName CHAR(30), category VARCHAR(20), date DATETIME, FOREIGN KEY (prodName, category) REFERENCES Product(name, category)

16 Example Create a database which can use in Seaport
The database consists of 3 tables: Sailors (sid integer, sname char, rating integer, age real) Reverses (sid, bid, day) Boats (bid integer, bname char, color char)

17 DROP command DROP TABLE BOATS DROP TABLE REVERSES DROP TABLE SAILORS

18 ALTER COMMAND ALTER TABLE Sailors ADD address CHAR(30)
ALTER TABLE Boats DROP colors

19 INDEX CREATE INDEX S ON Sailors (sid)
CREATE INDEX R ON REVERSES (sid, bid, day) CREATE INDEX B ON Boats (bid) DROP INDEX R

20 Example 1 Since Status WorksIn Professor Department
CREATE TABLE WorksIn ( Since DATE, attribute Status CHAR (10), attribute ProfId INTEGER, role (key of Professor) DeptId CHAR (4), role (key of Department) PRIMARY KEY (ProfId), -- since a professor works in at most one department FOREIGN KEY (ProfId) REFERENCES Professor (Id), FOREIGN KEY (DeptId) REFERENCES Department )

21 Example 2 Date Price Sold Project Part Supplier CREATE TABLE Sold (
Price INTEGER, attribute Date DATE, attribute ProjId INTEGER, role SupplierId INTEGER, role PartNumber INTEGER, role PRIMARY KEY (ProjId, SupplierId, PartNumber, Date), //WHY DATE? FOREIGN KEY (ProjId) REFERENCES Project, FOREIGN KEY (SupplierId) REFERENCES Supplier (Id), FOREIGN KEY (PartNumber) REFERENCES Part (Number) )

22 DML SELECT The basic format for the SELECT command is
SELECT <attribute list> FROM <table list> WHERE <condition>

23 Simple SQL Query SELECT * FROM Product WHERE category=‘Gadgets’
PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi SELECT * FROM Product WHERE category=‘Gadgets’ PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 “selection”

24 Examples Retrieve the birthdate and address of employee whose name is “John B. Smith” SELECT Bdate, Address FROM Employee WHERE Name = ‘John B. Smith’

25 Example Retrieve all Sailors name whose reverses boat id 103
SELECT sname FROM Sailors , Reverses WHERE Sailors.sid = Reverses.sid AND Reverses.bid=103

26 ORDER BY The Select command has sentential ORDER BY Select S.sname
FROM Sailors S, Reverses R WHERE S.sid = R.sid AND R.bid = 103 ORDER BY age DESC

27 The LIKE operator s LIKE p: pattern matching on strings
p may contain two special symbols: % = any sequence of characters _ = any single character Product(PName, Price, Category, Manufacturer) Find all products whose name mentions ‘gizmo’: SELECT * FROM Products WHERE PName LIKE ‘%gizmo%’

28 Eliminating Duplicates
Category Gadgets Photography Household SELECT DISTINCT category FROM Product Compare to: Category Gadgets Photography Household SELECT category FROM Product

29 Joins in SQL Connect two or more tables: What is the connection
PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Product Company Cname StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 What is the connection between them ?

30 Joins Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country) Find all countries that manufacture some product in the ‘Gadgets’ category. SELECT country FROM Product, Company WHERE manufacturer=cname AND category=‘Gadgets’

31 Joins Product (pname, price, category, manufacturer)
Purchase (buyer, seller, store, product) Person(persname, phoneNumber, city) Find names of people living in Seattle that bought some product in the ‘Gadgets’ category, and the names of the stores they bought such product from SELECT DISTINCT persname, store FROM Person, Purchase, Product WHERE persname=buyer AND product = pname AND city=‘Seattle’ AND category=‘Gadgets’

32 SQL Join Expression Styles
Database Systems 6e / Rob & Coronel

33 Additional clauses with JOIN
JOIN USING – return only the rows with matching vales in the column indicated in the USING clause This column must exist in both tables SELECT column-list FROM table1 JOIN table2 USING (common-column) JOIN ON – when the tables have no common attribute name but the columns have the same attribute type SELECT column-list FROM table1 JOIN table2 ON join-condition Database Systems 6e / Rob & Coronel

34 Equi-Join Example – alternative syntax
INNER JOIN clause is an alternative to WHERE clause, and is used to match primary and foreign keys. An INNER join will only return rows from each table that have matching rows in the other. This query produces same results as previous equi-join example.

35 Outerjoins Explicit joins in SQL = “inner joins”:
Product(name, category) Purchase(prodName, store) SELECT Product.name, Purchase.store FROM Product JOIN Purchase ON Product.name = Purchase.prodName Same as: SELECT Product.name, Purchase.store FROM Product, Purchase WHERE Product.name = Purchase.prodName But Products that never sold will be lost !

36 Product Purchase Name Category Gizmo gadget Camera Photo OneClick
ProdName Store Gizmo Wiz Camera Ritz Name Store Gizmo Wiz Camera Ritz OneClick NULL

37 Application Compute, for each product, the total number of sales in ‘September’ Product(name, category) Purchase(prodName, month, store) SELECT Product.name, count(*) FROM Product, Purchase WHERE Product.name = Purchase.prodName and Purchase.month = ‘September’ GROUP BY Product.name What’s wrong ?

38 Application Compute, for each product, the total number of sales in ‘September’ Product(name, category) Purchase(prodName, month, store) SELECT Product.name, count(*) FROM Product LEFT OUTER JOIN Purchase ON Product.name = Purchase.prodName and Purchase.month = ‘September’ GROUP BY Product.name Now we also get the products who sold in 0 quantity

39 Visualization of different join types with results returned in shaded area

40 Outer Joins Left outer join: Right outer join: Full outer join:
Include the left tuple even if there’s no match Right outer join: Include the right tuple even if there’s no match Full outer join: Include the both left and right tuples even if there’s no match

41 Outerjoins Left outer joins in SQL: Product(name, category)
Purchase(prodName, store) SELECT Product.name, Purchase.store FROM Product LEFT OUTER JOIN Purchase ON Product.name = Purchase.prodName

42 Subqueries Returning Relations
You can also use: s > ALL R s > ANY R EXISTS R Product ( pname, price, category, maker) Find products that are more expensive than all those produced By “Gizmo-Works” SELECT name FROM Product WHERE price > ALL (SELECT price FROM Purchase WHERE maker=‘Gizmo-Works’)

43 Correlated Queries Movie (title, year, director, length)
Find movies whose title appears more than once. correlation SELECT DISTINCT title FROM Movie AS x WHERE year <> ANY (SELECT year FROM Movie WHERE title = x.title); Note (1) scope of variables (2) this can still be expressed as single SFW

44 Complex Correlated Query
Product ( pname, price, category, maker, year) Find products (and their manufacturers) that are more expensive than all products made by the same manufacturer before 1972 Very powerful ! Also much harder to optimize. SELECT DISTINCT pname, maker FROM Product AS x WHERE price > ALL (SELECT price FROM Product AS y WHERE x.maker = y.maker AND y.year < 1972);

45 Aggregate Operators COUNT (*) COUNT ( [DISTINCT] A)
A is a column SUM ( [DISTINCT] A) AVG ( [DISTINCT] A) MAX (A) MIN (A) Count the number of sailors SELECT COUNT (*) FROM Sailors S

46 Find name and age of the oldest sailor(s)
SELECT S.sname, MAX (S.age) FROM Sailors S This is illegal, but why? Cannot combine a column with a value SELECT S.sname, S.age WHERE S.age = (SELECT MAX (S2.age) FROM Sailors S2)

47 Examples What is the average distance between plazas?
select avg(distfromprev) from plazas How many events are there? select count(*) from events  29 How many distinct times are there? select count(distinct occurredat) from events  24 How do we find the duplicates?

48 Aggregation: Count SELECT Count(*) FROM Product WHERE year > 1995
Except COUNT, all aggregations apply to a single attribute

49 Aggregation: Count COUNT applies to duplicates, unless otherwise stated: SELECT Count(category) same as Count(*) FROM Product WHERE year > 1995 Better: SELECT Count(DISTINCT category)

50 Aggregate functions GROUP BY & HAVING
GROUP BY for grouping the Query results Having to provide a condition on the group

51 Example SELECT Pnumber, Pname, COUNT(*) FROM PROJECT, WORKS_ON
WHERE Pnumber = PNO GROUP BY Pnumber, Pname HAVING COUNT(*) >2

52 Grouping and Aggregation
Usually, we want aggregations on certain parts of the relation. Purchase(product, date, price, quantity) Example 2: find total sales after 10/1 per product. SELECT product, Sum(price*quantity) AS TotalSales FROM Purchase WHERE date > “10/1” GROUPBY product Let’s see what this means…

53 Grouping and Aggregation
1. Compute the FROM and WHERE clauses. 2. Group by the attributes in the GROUPBY 3. Select one tuple for every group (and apply aggregation) SELECT can have (1) grouped attributes or (2) aggregates.

54 HAVING Clause Same query, except that we consider only products that had at least 100 buyers. SELECT product, Sum(price * quantity) FROM Purchase WHERE date > “9/1” GROUP BY product HAVING Sum(quantity) > 30 HAVING clause contains conditions on aggregates.

55 Find all authors who wrote at least 10 documents:
Attempt 1: with nested queries This is SQL by a novice SELECT DISTINCT Author.name FROM Author WHERE count(SELECT Wrote.url FROM Wrote WHERE Author.login=Wrote.login) > 10

56 Find all authors who wrote at least 10 documents:
Attempt 2: SQL style (with GROUP BY) This is SQL by an expert SELECT Author.name FROM Author, Wrote WHERE Author.login=Wrote.login GROUP BY Author.name HAVING count(wrote.url) > 10 No need for DISTINCT: automatically from GROUP BY

57 GROUP BY v.s. Nested Quereis
SELECT product, Sum(price*quantity) AS TotalSales FROM Purchase WHERE date > ‘10/1/2005’ GROUP BY product SELECT DISTINCT x.product, (SELECT Sum(y.price*y.quantity) FROM Purchase y WHERE x.product = y.product AND y.date > ‘10/1/2005’) AS TotalSales FROM Purchase x WHERE x.date > ‘10/1/2005’

58 SQL Sailors Using the following tables age rating sname Sid 45 7
Dustin 22 33 1 Brutus 29 55.5 8 Lubber 31 25.5 Andy 32 35 10 Rusty 58 Horatio 64 16 Zorba 71 40 9 74 3 Art 85 63.5 bob 95 Sailors

59 Example Boats Reverses Day bid Sid 10/10/98 101 22 102 10/8/98 103
10/7/98 104 11/10/98 31 10/6/98 10/12/98 9/5/98 64 9/8/98 74 Boats Color Banem Bid Blue Interlake 101 Red 102 Green Clipper 103 Marine 104 Reverses

60 Queries Find the names and ages of all sailors
Find all sailors with rating above 7 Find the name of sailors who have reserved boat number 104

61

62 Quiz Write an SQL query for following, and show the result on the example tables: Find all course names that were not taught in 1997 List the professor names along with all the departments ids where a professor has taught Find the names of students who took courses in all the departments that offered a course in Fall of 1995 or 1997.

63 Exercises Product (pname, price, category, manufacturer)
Purchase (buyer, seller, store, product) Company (cname, stock price, country) Person(per-name, phone number, city) Ex #1: Find people who bought telephony products. Ex #2: Find names of people who bought American products Ex #3: Find names of people who bought American products and they live in Seattle. Ex #4: Find people who have both bought and sold something. Ex #5: Find people who bought stuff from Joe or bought products from a company whose stock prices is more than $50.

64 Database Systems 6e / Rob & Coronel
UNION Query Combine two companies customer lists where they have names in common so that the final list has no duplicate names Column names and their attributes must be the same SELECT <COLUMN NAMES> FROM CUSTOMER UNION SELECT <COLUMN NAMES> FROM CUSTOMER_2; Can include more than two tables where applicable SELECT <COLUMN NAMES> FROM T1 UNION SELECT <COLUMN NAMES> FROM T2 UNION SELECT <COLUMN NAMES> FROM T3; Database Systems 6e / Rob & Coronel

65 Database Systems 6e / Rob & Coronel
Intersect Query Find the rows that are in both tables Find rows based on another select Not available in MS Access Alternative SELECT CUS_CODE FROM CUSTOMER WHERE CUS_AREACODE=‘615’ AND CUS_CODE IN (SELECT DISTINCT CUS_CODE FROM INVOICE); Database Systems 6e / Rob & Coronel

66 Database Systems 6e / Rob & Coronel
Minus Query Combines rows from two queries and returns only those rows that appear in the first set but not the second Alternative – use NOT IN Customers located in area code 615 minus the ones who have made purchases i.e., these “615” customers did not make purchases Database Systems 6e / Rob & Coronel

67 1. INTERSECT and EXCEPT: (SELECT R.A, R.B FROM R) INTERSECT
INTERSECT and EXCEPT: not in SQL Server 1. INTERSECT and EXCEPT: If R, S have no duplicates, then can write without subqueries (HOW ?) (SELECT R.A, R.B FROM R) INTERSECT (SELECT S.A, S.B FROM S) SELECT R.A, R.B FROM R WHERE EXISTS(SELECT * FROM S WHERE R.A=S.A and R.B=S.B) (SELECT R.A, R.B FROM R) EXCEPT (SELECT S.A, S.B FROM S) SELECT R.A, R.B FROM R WHERE NOT EXISTS(SELECT * FROM S WHERE R.A=S.A and R.B=S.B)

68 Null Values Unexpected behavior: SELECT * FROM Person
Some Persons are not included ! SELECT * FROM Person WHERE age < 25 OR age >= 25

69 Null Values Can test for NULL explicitly: Now it includes all Persons
x IS NULL x IS NOT NULL Now it includes all Persons SELECT * FROM Person WHERE age < 25 OR age >= 25 OR age IS NULL

70 Mutating (non-read-only) queries
Deletion Deletes whole tuples Insertion Inserts whole tuples Update Changes values of attributes Can generally do these to tables but not to views or other derived entities Note that renaming is not in itself derivation So a renamed relation can be mutated like the original

71 Update update name set assignment where P
where clause is optional (selects tuples to be updated) Give Jane Swift a $20 balance update subscribers set balance = 20 where firstname=“Jane” and lastname=“Swift” Give every subscriber a $3 rebate update subscribers set balance = balance + 3

72 Update examples UPDATE P SET Color = ‘Yellow’ Weight = Weight + 5
City = NULL WHERE P# = 2

73 SELECT Subquery Examples
Database Systems 6e / Rob & Coronel

74 Deletion delete from name where P
Delete all events from transponder 72 delete from events where tid=72 Delete all events relating to George Bush delete from events where tid in select from transponders as t, subscribers as s where t.tid = s.tid and s.firstname=“George” and s.lastname=“Bush”

75 Delete example DELETE FROM S WHERE S# =1

76 Insertions General form: INSERT INTO R(A1,…., An) VALUES (v1,…., vn)
Example: Insert a new purchase to the database: INSERT INTO Purchase(buyer, seller, product, store) VALUES (‘Joe’, ‘Fred’, ‘wakeup-clock-espresso-machine’, ‘The Sharper Image’) Missing attribute  NULL. May drop attribute names if give them in order.

77 Insert example INSERT INTO P(P#, City , Weight)
VALUES (7 , ‘athens’, )

78 Grant & revoke operations
the format are GRANT operation ON table TO user REVOKE operation FROM user

79 Examples GRANT INSERT, DELETE ON TABLE reserves TO ahmed
GRANT ALL ON TABLE saliros TO hassan REVOKE SELECT ON TABLE boats FROM manal

80 Grant Example GRANT SELECT ON TABLE S TO u3 WITH GRANT OPTION
REVOKE DELETE ON TABLE S FROM U2

81 Starwars Exercises char(name, race, homeworld, affiliation)
planets(name, type, affiliation) timetable(cname, pname, movie, arrival, departure) Which planet does Princess Leia go to in movie3? SELECT distinct pname FROM timetable WHERE cname ='Princess Leia' and movie=3;

82 Starwars Exercises char(name, race, homeworld, affiliation)
planets(name, type, affiliation) timetable(cname, pname, movie, arrival, departure) How many humans stay on Dagobah in movie 3? SELECT count(*) FROM timetable, characters WHERE movie=3 and pname =‘Dagobah’ and timetable.cname=characters.name and characters.race=‘Human’;

83 Starwars Exercises char(name, race, homeworld, affiliation)
planets(name, type, affiliation) timetable(cname, pname, movie, arrival, departure) Who has been to his/her homeworld in movie 2? SELECT distinct c.name FROM characters c, timetable t WHERE c.name=t.cname and t.pname=c.homeworld and movie=2;

84 Starwars Exercises char(name, race, homeworld, affiliation)
planets(name, type, affiliation) timetable(cname, pname, movie, arrival, departure) Find distinct names of the planets visited by those of race “droid”. SELECT distinct t.pname FROM char c, timetable t WHERE c.name=t.cname and c.race=‘droid’;

85 Starwars Exercises char(name, race, homeworld, affiliation)
planets(name, type, affiliation) timetable(cname, pname, movie, arrival, departure) For each character and for each neutral planet, how much time total did the character spend on the planet? SELECT c.name, p.name, SUM(t.departure-t.arrival) as amount FROM characters c, timetable t, planets p WHERE t.cname=c.name and t.pname=p.name and p.affiliation='neutral' GROUP BY c.name, p.name;

86 EXERCISE 1: Queries First and last name of employees who have no supervisor. First and last name of employees supervised by Franklin Wong. Last name of employees who have dependents. Last name of employees who have daughters. Last name of employees in department 5 who work more than 10 hours/week on ProductX. Last name of supervisors of employees in department who work more than 10 hours/week on ProductX. First and last names of all department managers. Salaries of all employees who have worked on the Reorganization project. SSN of all employees who have worked on a project that is controlled by a department different than the department that they are assigned to. Last name of all employees who are not married.

87 EXERCISE 1: Schema

88 EXERCISE 1: Instance

89 EXERCISE 2: Queries List all airplane types that can land at any airport in San Francisco. List the ids and number of seats for all airplanes that can land at any airport in Chicago. List the name and phone number of all customers with a seat reserved on a flight that leaves Chicago O’Hara airport (ORD) on October 31, 2008. List all airlines that have seats available for flights leaving Los Angeles (LAX) on September 25, 2008. List all airlines that operate at San Jose International Airport (SJC).

90 Exercise 2: Schema

91 EXERCISE 3: Queries Count the number of overdue books.
How many books by author Harry Crews are in the database? Determine the number of library cards assigned to each borrower phone number. Find names of all borrowers who do not have any book loans. Do any library branches have every book?

92 EXERCISE 3: Schema


Download ppt "Database SQL."

Similar presentations


Ads by Google