Lecture 4: SQL Thursday, January 11, 2001.

Slides:



Advertisements
Similar presentations
1 Lecture 5: SQL Schema & Views. 2 Data Definition in SQL So far we have see the Data Manipulation Language, DML Next: Data Definition Language (DDL)
Advertisements

1 Lecture 02: SQL. 2 Outline Data in SQL Simple Queries in SQL (6.1) Queries with more than one relation (6.2) Recomeded reading: Chapter 3, Simple Queries.
SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: SQL92, SQL2, SQL3. Vendors support.
Relational Algebra (end) SQL April 19 th, Complex Queries Product ( pid, name, price, category, maker-cid) Purchase (buyer-ssn, seller-ssn, store,
1 Lecture 12: SQL Friday, October 26, Outline Simple Queries in SQL (5.1) Queries with more than one relation (5.2) Subqueries (5.3) Duplicates.
1 Lecture 03: Advanced SQL. 2 Outline Unions, intersections, differences Subqueries, Aggregations, NULLs Modifying databases, Indexes, Views Reading:
1 Data Definition in SQL So far we have see the Data Manipulation Language, DML Next: Data Definition Language (DDL) Data types: Defines the types. Data.
SQL April 25 th, Agenda Grouping and aggregation Sub-queries Updating the database Views More on views.
1 Lecture 05: SQL Wednesday, October 8, Outline Outer joins (6.3.8) Database Modifications (6.5) Defining Relation Schema in SQL (6.6) Indexes.
1 INTERSECT and EXCEPT: (may no be in MySQL) (SELECT R.A, R.B FROM R) INTERSECT (SELECT S.A, S.B FROM S) (SELECT R.A, R.B FROM R) INTERSECT (SELECT S.A,
1 Lecture 03: SQL Friday, January 7, Administrivia Have you logged in IISQLSRV yet ? HAVE YOU CHANGED YOUR PASSWORD ? Homework 1 is now posted.
1 Lecture 02: Basic SQL. 2 Outline Data in SQL Simple Queries in SQL Queries with more than one relation Reading: Chapter 3, “Simple Queries” from SQL.
Correlated Queries SELECT title FROM Movie AS Old WHERE year < ANY (SELECT year FROM Movie WHERE title = Old.title); Movie (title, year, director, length)
1 Lecture 3: More SQL Friday, January 9, Agenda Homework #1 on the web site today. Sign up for the mailing list! Next Friday: –In class ‘activity’
Union, Intersection, Difference (SELECT name FROM Person WHERE City=“Seattle”) UNION (SELECT name FROM Person, Purchase WHERE buyer=name AND store=“The.
Complex Queries (1) Product ( pname, price, category, maker)
Integrity Constraints An important functionality of a DBMS is to enable the specification of integrity constraints and to enforce them. Knowledge of integrity.
Exercises Product ( pname, price, category, maker) Purchase (buyer, seller, store, product) Company (cname, stock price, country) Person( per-name, phone.
1 Lecture 4: More SQL Monday, January 13th, 2003.
1 Lecture 7: End of Normal Forms Outerjoins, Schema Creation and Views Wednesday, January 28th, 2004.
SQL (almost end) April 26 th, Agenda HAVING clause Views Modifying views Reusing views.
SQL April 22 th, Agenda Union, intersections Sub-queries Modifying the database Views Modifying views Reusing views.
1 SQL cont.. 2 Outline Unions, intersections, differences (6.2.5, 6.4.2) Subqueries (6.3) Aggregations (6.4.3 – 6.4.6) Hint for reading the textbook:
IM433-Industrial Data Systems Management Lecture 5: SQL.
More SQL: Complex Queries, Triggers, Views, and Schema Modification UMM AL QURA UNIVERSITY College of Computer Dr. Ali Al Najjar 1.
1 Lecture 04: SQL Wednesday, January 11, Outline Two Examples Nulls (6.1.6) Outer joins (6.3.8) Database Modifications (6.5)
SQL. SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: ANSI SQL, SQL92 (a.k.a.
1 Introduction to Database Systems CSE 444 Lecture 02: SQL September 28, 2007.
1 Lecture 02: SQL Friday, September 30, Administrivia Homework 1 is out. Due: Wed., Oct. 12 Did you login on IISQLSRV ? Did you change your password.
1 Introduction to Database Systems CSE 444 Lecture 04: SQL April 7, 2008.
1 Lecture 5: Outerjoins, Schema Creation and Views Wednesday, January 15th, 2003.
Aggregation SELECT Sum(price) FROM Product WHERE manufacturer=“Toyota” SQL supports several aggregation operations: SUM, MIN, MAX, AVG, COUNT Except COUNT,
1 Lecture 06 Data Modeling: E/R Diagrams Wednesday, January 18, 2006.
1 Lecture 05: SQL Wednesday, October 8, Outline Database Modifications (6.5) Defining Relation Schema in SQL (6.6) Indexes Defining Views (6.7)
SQL. SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: ANSI SQL, SQL92 (a.k.a.
SQL.
Lecture 05: SQL Wednesday, January 12, 2005.
Cours 7: Advanced SQL.
Lecture 04: SQL Monday, January 10, 2005.
Relational Algebra at a Glance
Modifying the Database
Database Systems Subqueries, Aggregation
Monday 3/27 and Wednesday 3/29, 2006
Introduction to Database Systems CSE 444 Lecture 04: SQL
Lecture 2 (cont’d) & Lecture 3: Advanced SQL – Part I
Introduction to Database Systems CSE 444 Lecture 03: SQL
Introduction to SQL Wenhao Zhang October 5, 2018.
Introduction to Database Systems CSE 444 Lecture 03: SQL
CSE544 SQL Wednesday, March 31, 2004.
Building a Database Application
SQL Introduction Standard language for querying and manipulating data
Lecture 12: SQL Friday, October 20, 2000.
Lectures 3: Introduction to SQL Part II
Introduction to Database Systems CSE 444 Lecture 02: SQL
Lectures 5: Introduction to SQL 4
Where are we? Until now: Modeling databases (ODL, E/R): all about the schema Now: Manipulating the data: queries, updates, SQL Then: looking inside -
Lectures 6: Introduction to SQL 5
Integrity Constraints
Lecture 3 Monday, April 8, 2002.
Lecture 06: SQL Monday, October 11, 2004.
Lecture 4: SQL Wednesday, April 10, 2002.
Lecture 03: SQL Friday, October 3, 2003.
Lecture 3: Relational Algebra and SQL
CSE544 SQL Monday, April 5, 2004.
Lecture 04: SQL Monday, October 6, 2003.
Lecture 05: SQL Wednesday, October 9, 2002.
Lecture 14: SQL Wednesday, October 31, 2001.
Presentation transcript:

Lecture 4: SQL Thursday, January 11, 2001

Outline Semantics Nested Queries Aggregation Database Modifications Defining a Relation Schema in SQL View Definitions Reading: 5.2, 5.3, 5.4, 5.5, 5.6

Meaning (Semantics) of SQL Queries SELECT a1, a2, …, ak FROM R1 AS x1, R2 AS x2, …, Rn AS xn WHERE Conditions 1. Nested loops: Answer = {} for x1 in R1 do for x2 in R2 do ….. for xn in Rn do if Conditions then Answer = Answer U {(a1,…,ak)} return Answer

Meaning (Semantics) of SQL Queries SELECT a1, a2, …, ak FROM R1 AS x1, R2 AS x2, …, Rn AS xn WHERE Conditions 2. Parallel assignment Answer = {} for all assignments x1 in R1, …, xn in Rn do if Conditions then Answer = Answer U {(a1,…,ak)} return Answer Doesn’t impose any order !

Meaning (Semantics) of SQL Queries SELECT a1, a2, …, ak FROM R1 AS x1, R2 AS x2, …, Rn AS xn WHERE Conditions 3. Translation to Relational algebra: Pa1,,…,ak ( s Conditions (R1 x R2 x … x Rn)) Select-From-Where queries are precisely Select-Project-Join

First Unintuitive SQLism SELECT R.A FROM R, S, T WHERE R.A=S.A OR R.A=T.A Looking for R ∩ (S U T) But what happens if T is empty?

Union, Intersection, Difference (SELECT name FROM Person WHERE City=“Seattle”) UNION FROM Person, Purchase WHERE buyer=name AND store=“The Bon”) Similarly, you can use INTERSECT and EXCEPT. You must have the same attribute names (otherwise: rename).

Conserving Duplicates The UNION, INTERSECTION and EXCEPT operators operate as sets, not bags. (SELECT name FROM Person WHERE City=“Seattle”) UNION ALL keeps duplicates FROM Person, Purchase WHERE buyer=name AND store=“The Bon”)

Subqueries A subquery producing a single tuple: SELECT Purchase.product FROM Purchase WHERE buyer = (SELECT name FROM Person WHERE ssn = “123456789”); In this case, the subquery returns one value. If it returns more, it’s a run-time error.

Can say the same thing without a subquery: SELECT Purchase.product FROM Purchase, Person WHERE buyer = name AND ssn = “123456789” Is this query equivalent to the previous one ?

Subqueries Returning Relations Find companies who manufacture products bought by Joe Blow. SELECT Company.name FROM Company, Product WHERE Company.name=maker AND Product.name IN (SELECT product FROM Purchase WHERE buyer = “Joe Blow”); Here the subquery returns a set of values

Subqueries Returning Relations Equivalent to: SELECT Company.name FROM Company, Product, Purchase WHERE Company.name=maker AND Product.name = product AND buyer = “Joe Blow” Is this query equivalent to the previous one ?

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

Question for Database Fans Can we express this query as a single SELECT-FROM-WHERE query, without subqueries ? Hint: show that all SFW queries are monotone (figure out what this means). A query with ALL is not monotone

Conditions on Tuples SELECT Company.name FROM Company, Product WHERE Company.name=maker AND (Product.name,price) IN (SELECT product, price) FROM Purchase WHERE buyer = “Joe Blow”);

Correlated Queries Movie (title, year, director, length) Find movies whose title appears more than once. correlation SELECT 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

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 SELECT pname, maker FROM Product AS x WHERE price > ALL (SELECT price FROM Product AS y WHERE x.maker = y.maker AND y.year < 1972); Powerful, but much harder to optimize !

Exercises: write RA and SQL expressions Product ( pname, price, category, maker) 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 did not buy French products Ex #4: Find names of people who bought American products and they live in Seattle. Ex #5: Find people who bought stuff from Joe or bought products from a company whose stock prices is more than $50.

Simple Aggregation SELECT Sum(price) FROM Product WHERE maker=“Toyota” SQL supports several aggregation operations: SUM, MIN, MAX, AVG, COUNT

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

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

Simple Aggregation: Sum Purchase(product, date, price, quantity) find total sales for the entire database SELECT Sum(price * quantity) FROM Purchase find total sales of bagels WHERE product = ‘bagel’

Simple Aggregations Answer: 0.85*15 + 0.85*20 = 29.75

Aggregation with Grouping Usually, we want aggregations on certain parts of the relation. Purchase(product, date, price, quantity) find total sales after 9/1 per product. SELECT product, Sum(price*quantity) AS TotalSales FROM Purchase WHERE date > “9/1” GROUPBY product

Aggregation with Grouping: Semantics 1. Compute the relation (I.e., the FROM and WHERE). 2. Group by the attributes in the GROUPBY 3. Construct one tuple for every group, by applying aggregation SELECT can have grouped attributes and/or aggregates.

First compute the relation (date > “9/1”) then group by product:

Then, aggregate SELECT product, Sum(price*quantity) AS TotalSales FROM Purchase WHERE date > “9/1” GROUPBY product

Another Example SELECT product, Sum(price * quantity) AS SumSales Max(quantity) AS MaxQuantity FROM Purchase GROUP BY product For every product, what is the total sales and max quantity sold?

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 count(*) > 100 HAVING clause contains conditions on aggregates.

General form of Grouping and Aggregation SELECT S FROM R1,…,Rn WHERE C1 GROUP BY a1,…,ak HAVING C2 S = may contain attributes a1,…,ak and/or any aggregates but NO OTHER ATTRIBUTES C1 = is any condition on the attributes in R1,…,Rn C2 = is any condition on aggregate expressions

Semantics Revisited SELECT S FROM R1,…,Rn WHERE C1 GROUP BY a1,…,ak HAVING C2 Semantics in 4 steps: Compute the FROM-WHERE part, obtain a table with all attributes in R1,…,Rn Group by the attributes a1,…,ak Compute the aggregates in C2 and keep only groups satisfying C2 Compute aggregates in S and return the result

Modifying the Database We have 3 kinds of modifications: Insertions Deletions Updates

Insertions General form: INSERT INTO R(A1,…., An) VALUES (v1,…., vn) NULL for missing values Can drop attribute names if given in right order Example: Insert a new purchase to the database: INSERT INTO Purchase(buyer, seller, product, store) VALUES (“Joe”, “Fred”, “gizmo”, “GizmoStore”)

More Interesting Insertions INSERT INTO PRODUCT(name) SELECT DISTINCT spName FROM SalesProduct WHERE price > 100 The query replaces the VALUES keyword. Note: the order of querying and inserting matters (next)

Querying and Inserting Product(name, listPrice, category) Purchase(prodName, buyerName, price) One expects that prodName is a name occurring in Product foreign key But suppose the database became inconsistent, needs fixed: prodName buyerName price camera John 200 gizmo Smith 80 225 name listPrice category gizmo 100 gadgets

Querying and Inserting INSERT INTO Product(name) SELECT DISTINCT prodName FROM Purchase WHERE prodName NOT IN (SELECT name FROM Product) name listPrice category gizmo 100 Gadgets camera -

Querying and Inserting INSERT INTO Product(name, listPrice) SELECT DISTINCT prodName, price FROM Purchase WHERE prodName NOT IN (SELECT name FROM Product) name listPrice category gizmo 100 Gadgets camera 200 - camera ?? 225 ?? Depends on the implementation Order matters.

Deletions DELETE FROM PURCHASE WHERE seller = “Joe” AND product = “Brooklyn Bridge” Factoid about SQL: there is no way to delete only a single occurrence of a tuple that appears twice in a relation.

Updates UPDATE PRODUCT SET price = price/2 WHERE Product.name IN (SELECT product FROM Sales WHERE Date = today);

Data Definition in SQL So far, SQL operations on the data. Data Manipulation Language (DML) Data definition: defining the schema. Data Definition Language (DDL) Define data types Create/delete/modify tables Defining views

Data Types in SQL Character strings (fixed of varying length) Bit strings (fixed or varying length) Integer (SHORTINT) Floating point Dates and times Domains will be used in table declarations. To reuse domains: CREATE DOMAIN address AS VARCHAR(55)

Creating Tables CREATE TABLE Person( name VARCHAR(30), social-security-number INTEGER, age SHORTINT, city VARCHAR(30), gender BIT(1), Birthdate DATE );

Creating Tables with Default Values Specifying default values: CREATE TABLE Person( name VARCHAR(30), social-security-number INTEGER, age SHORTINT DEFAULT 100, city VARCHAR(30) DEFAULT “Seattle”, gender CHAR(1) DEFAULT “?”, birthdate DATE) The default of defaults: NULL

Deleting or Modifying a Table Deleting: DROP Person; Altering: ALTER TABLE Person ADD phone CHAR(16); ALTER TABLE Person DROP age;

Defining Views Views are relations, except that they are not physically stored. For presenting different information to different users Employee(ssn, name, department, project, salary) CREATE VIEW Developers AS SELECT name, project FROM Employee WHERE department = “Development” Payroll has access to Employee, others only to Developers

A Different View Person(name, city) Purchase(buyer, seller, product, store) Product(name, maker, category) CREATE VIEW Seattle-view AS SELECT buyer, seller, product, store FROM Person, Purchase WHERE Person.city = “Seattle” AND Person.name = Purchase.buyer We have a new virtual table: Seattle-view(buyer, seller, product, store)

A Different View Person(name, city) Purchase(buyer, seller, product, store) Product(name, maker, category) We can later use the view: SELECT name, store FROM Seattle-view, Product WHERE Seattle-view.product = Product.name AND Product.category = “shoes” Some views are updateable, some are not

What Happens When We Query a View ? SELECT Product.name, Seattle-view.store FROM Seattle-view, Product WHERE Seattle-view.product = Product.name AND Product.category = “shoes” SELECT Product.name, Purchase.store FROM Person, Purchase, Product WHERE Person.city = “Seattle” AND Person.name = Purchase.buyer AND Purchase.poduct = Product.name AND View expansion