M.P. Johnson, DBMS, Stern/NYU, Sp20041 C20.0046: Database Management Systems Lecture #10 Matthew P. Johnson Stern School of Business, NYU Spring, 2004.

Slides:



Advertisements
Similar presentations
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.
Advertisements

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,
Relational Algebra Maybe -- SQL. Confused by Normal Forms ? 3NF BCNF 4NF If a database doesn’t violate 4NF (BCNF) then it doesn’t violate BCNF (3NF) !
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.
M.P. Johnson, DBMS, Stern/NYU, Spring C : Database Management Systems Lecture #10 Matthew P. Johnson Stern School of Business, NYU Spring,
M.P. Johnson, DBMS, Stern/NYU, Spring C : Database Management Systems Lecture #6 M.P. Johnson Stern School of Business, NYU Spring, 2008.
M.P. Johnson, DBMS, Stern/NYU, Sp20041 C : Database Management Systems Lecture #9 Matthew P. Johnson Stern School of Business, NYU Spring, 2004.
SQL. 1.SQL is a high-level language, in which the programmer is able to avoid specifying a lot of data-manipulation details that would be necessary in.
Matthew P. Johnson, OCL2, CISDD CUNY, January OCL2 Oracle 10g: SQL & PL/SQL Session #3 Matthew P. Johnson CISDD, CUNY January, 2005.
M.P. Johnson, DBMS, Stern/NYU, Spring C : Database Management Systems Lecture #7 M.P. Johnson Stern School of Business, NYU Spring, 2008.
Matthew P. Johnson, OCL1, CISDD CUNY, F20041 OCL1 Oracle 8i: SQL & PL/SQL Session #3 Matthew P. Johnson CISDD, CUNY Fall, 2004.
Matthew P. Johnson, OCL5, CISDD CUNY, Sept OCL4 Oracle 10g: SQL & PL/SQL Session #2 Matthew P. Johnson CISDD, CUNY June, 2005.
M.P. Johnson, DBMS, Stern/NYU, Spring C : Database Management Systems Lecture #9 Matthew P. Johnson Stern School of Business, NYU Spring, 2005.
Matthew P. Johnson, OCL4, CISDD CUNY, Sept OCL4 Oracle 10g: SQL & PL/SQL Session #3 Matthew P. Johnson CISDD, CUNY June, 2005.
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.
M.P. Johnson, DBMS, Stern/NYU, Spring C : Database Management Systems Lecture #15 M.P. Johnson Stern School of Business, NYU Spring, 2005.
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 2: SQL Wednesday, January 7, Agenda Leftovers from Monday The relational model (very quick) SQL Homework #1 given out later this week.
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’
1 Information Systems Chapter 6 Database Queries.
Complex Queries (1) Product ( pname, price, category, maker)
One More Normal Form Consider the dependencies: Product Company Company, State Product Is it in BCNF?
Relation Decomposition A, A, … A 12n Given a relation R with attributes Create two relations R1 and R2 with attributes B, B, … B 12m C, C, … C 12l Such.
CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006.
Integrity Constraints An important functionality of a DBMS is to enable the specification of integrity constraints and to enforce them. Knowledge of integrity.
+ From Relational Algebra to SQL W2013 CSCI 2141.
Exercises Product ( pname, price, category, maker) Purchase (buyer, seller, store, product) Company (cname, stock price, country) Person( per-name, phone.
1. Midterm summary Types of data on the web: unstructured, semi- structured, structured Scale and uncertainty are key features Main goals are to model,
1 Database Systems Lecture #6 Yan Pan School of Software, SYSU 2011.
IM433-Industrial Data Systems Management Lecture 5: SQL.
Intro. to SQL DSC340 Mike Pangburn. Learning Objectives Understand the data-representation terminology underlying relational databases Understand core.
More SQL: Complex Queries, Triggers, Views, and Schema Modification UMM AL QURA UNIVERSITY College of Computer Dr. Ali Al Najjar 1.
Lectures 2&3: Introduction to SQL. Lecture 2: SQL Part I Lecture 2.
SQL SQL Review. SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: ANSI SQL, SQL92.
SQL. SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: ANSI SQL, SQL92 (a.k.a.
Lecture 2: E/R Diagrams and the Relational Model Wednesday, April 3 rd, 2002.
© D. Wong Normalization  Purpose: process to eliminate redundancy in relations due to functional or multi-valued dependencies.  Decompose relation.
Hassan Tariq MULTIPLE TABLES: SQL provides a convenient operation to retrieve information from multiple tables.SQL provides a convenient operation to.
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 CSEP 544 Lecture #1 March 29, 2004 Alon Halevy.
Lectures 2&3: Introduction to SQL. Lecture 2: SQL Part I Lecture 2.
Hassan Tariq INTRODUCTION TO SQL What is SQL? –When a user wants to get some information from a database file, he can issue a query. – A query is a user–request.
SQL. SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: ANSI SQL, SQL92 (a.k.a.
CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database Management 11 th Edition Jeffrey A. Hoffer,
Standard language for querying and manipulating data Structured Query Language Many standards out there: ANSI SQL, SQL92 (a.k.a. SQL2), SQL99 (a.k.a. SQL3),
SQL.
Lecture 05: SQL Wednesday, January 12, 2005.
Relational Algebra at a Glance
Server-Side Application and Data Management IT IS 3105 (FALL 2009)
SQL Introduction Standard language for querying and manipulating data
Lecture 2 (cont’d) & Lecture 3: Advanced SQL – Part I
Introduction to SQL Wenhao Zhang October 5, 2018.
CSE544 SQL Wednesday, March 31, 2004.
SQL Introduction Standard language for querying and manipulating data
Lecture 12: SQL Friday, October 20, 2000.
Lectures 3: Introduction to SQL 2
Introduction to Database Systems CSE 444 Lecture 02: SQL
Lecture 4: SQL Thursday, January 11, 2001.
Integrity Constraints
Lecture 3 Monday, April 8, 2002.
CS639: Data Management for Data Science
OCL3 Oracle 10g: SQL & PL/SQL Session #3
Lecture 03: SQL Friday, October 3, 2003.
Lecture 3: Relational Algebra and SQL
Presentation transcript:

M.P. Johnson, DBMS, Stern/NYU, Sp20041 C : Database Management Systems Lecture #10 Matthew P. Johnson Stern School of Business, NYU Spring, 2004

M.P. Johnson, DBMS, Stern/NYU, Sp Agenda Last time: R.A., Bags This time: 1. Finish R.A. 2. Begin SQL Project Part 2 due now Something else assigned soon

M.P. Johnson, DBMS, Stern/NYU, Sp Relational Algebra Review Five basic operators:  Union:  Intersection: Difference: -  Selection:   Projection:   Cartesian Product:  Extended operators:  Joins (equijoin, theta join, semijoin, outerjoin)  Renaming:   Extended projection   Sorting   Grouping-and-aggregation op 

M.P. Johnson, DBMS, Stern/NYU, Sp Sorting So far, everything’s an unordered bag But sometimes order is nice Sort op  L (R) produces a list, not a bag No operators operate on lists   if sort called, generally last op Subscript L = a 1,a 2,… in op is the list of attributes to sort on  Rows sorted by attributes  Rows with same a 1 value sorted by a 2, etc.

M.P. Johnson, DBMS, Stern/NYU, Sp Outerjoin Like L ⋈ R except that dangling tuples are included, padded with nulls Left outerjoin: dangling tuples from L are include  Nulls appear “on the right” Right outerjoin: dangling tuples from R are included  Nulls appear “on the left”

M.P. Johnson, DBMS, Stern/NYU, Sp Constraints on Relations (5.5) Ref. integ., FDs, other constraints are expressible in RA Two basic tools: 1. R =   Assert R is empty 2. R  S  Assert R is a subset of S NB: They’re equivalent R  S iff R – S =  R =  iff R  S-S (for arbitrary S)

M.P. Johnson, DBMS, Stern/NYU, Sp Expressing referential integrity Relations:  Reps(ssn, name, etc.)  Clients(ssn, name, rssn) Suppose we require: each client gets a sales rep a client’s row contains an rssn  must have a rep with that ssn How to require this in RA? Every Clients.rssn must be in the set of Reps.ssns  rssn (Clients)   ssn (Reps) Or:  rssn (Clients) –  ssn (Reps) = 

M.P. Johnson, DBMS, Stern/NYU, Sp Expressing referential integrity Also works for multiple attributes Relations: StarsIn(SName,Title,Year) Movies(Title, Year, Length, Studio) Require: every movie referenced by StarsIn to exist Write:  Title,Year (StarsIn)   Title,Year (Movies)

M.P. Johnson, DBMS, Stern/NYU, Sp Expressing FDs Relation: Employees(name,ssn,address,gender, etc.) Has FD: ssn  address What does the FD mean? No matter how we choose two rows, if they agree on ssn, then they agree on address So, strategy: choose pairs all possible ways; Select pairs that agree on ssn but not address; Check how many we get First, rename one copy to E1 and one to E2   E1 (Employees),  E2 (Employees) Then:  E1.ssn=E2.ssn AND E1.address != E2.address (E1 x E2) = 

M.P. Johnson, DBMS, Stern/NYU, Sp Expressing domain constraints Constraint on legal values for attributes Employees(name,ssn,address,gender etc.) Gender should be M/F Select bad ones and check count  gender!=‘F’ AND gender!=‘M’ (Employees) = 

M.P. Johnson, DBMS, Stern/NYU, Sp Expressing other constraints Relations: MovieExecs(name, address, ssn, netWorth) Studios(name, address, presSsn) Constraint: Studio presidents must be worth at leat $10,000,000 First, theta-join presSsn to ssn, then select ones w/ < $10M, then check count:  netWorth< (Studio ⋈ presSsn=ssn MEs) =  Or: Select MEs w/ >= $10M, then check that they contain all studio presidents:  presSsn (Studios)  ssn (  netWorth< (MEs))

M.P. Johnson, DBMS, Stern/NYU, Sp Recap: You are here First part of course is done: conceptual foundations You now know:  E/R Model  Relational Model  Relational Algebra You now know how to:  Capture part of world as an E/R model  Convert E/R models to relational models  Convert relational models to good (normal) forms  Express queries in relational algebra Next:  Create, update, query SQL tables  Write SQL/DB-connected applications

M.P. Johnson, DBMS, Stern/NYU, Sp Next topic: SQL (6.1) Standard language for querying and manipulating data Structured Query Language Many standards: ANSI SQL, SQL92/SQL2, SQL3/SQL99 Vendors support various subsets/extensions We’ll do SQL99/Oracle Basic form (many more bells and whistles in addition): SELECT attributes FROM relations (possibly multiple, joined) WHERE conditions (selections) SELECT attributes FROM relations (possibly multiple, joined) WHERE conditions (selections)

M.P. Johnson, DBMS, Stern/NYU, Sp Data Types in SQL Characters:  CHAR(20)-- fixed length  VARCHAR(40)-- variable length Numbers:  BIGINT, INT, SMALLINT, TINYINT  REAL, FLOAT -- differ in precision  MONEY Times and dates:  DATE  DATETIME-- SQL Server

M.P. Johnson, DBMS, Stern/NYU, Sp “Tables” PNamePriceCategoryManufacturer Gizmo$19.99GadgetsGizmoWorks Powergizmo$29.99GadgetsGizmoWorks SingleTouch$149.99PhotographyCanon MultiTouch$203.99HouseholdHitachi Product Attribute names Table name Tuples or rows

M.P. Johnson, DBMS, Stern/NYU, Sp Simple SQL Query PNamePriceCategoryManufacturer Gizmo$19.99GadgetsGizmoWorks Powergizmo$29.99GadgetsGizmoWorks SingleTouch$149.99PhotographyCanon MultiTouch$203.99HouseholdHitachi SELECT * FROM Product WHERE category=‘Gadgets’ Product PNamePriceCategoryManufacturer Gizmo$19.99GadgetsGizmoWorks Powergizmo$29.99GadgetsGizmoWorks “selection”

M.P. Johnson, DBMS, Stern/NYU, Sp Simple SQL Query PNamePriceCategoryManufacturer Gizmo$19.99GadgetsGizmoWorks Powergizmo$29.99GadgetsGizmoWorks SingleTouch$149.99PhotographyCanon MultiTouch$203.99HouseholdHitachi SELECT PName, Price, Manufacturer FROM Product WHERE Price > 100 Product PNamePriceManufacturer SingleTouch$149.99Canon MultiTouch$203.99Hitachi “selection” and “projection”

M.P. Johnson, DBMS, Stern/NYU, Sp A Notation for SQL Queries SELECT Name, Price, Manufacturer FROM Product WHERE Price > 100 Product(PName, Price, Category, Manfacturer) Answer(PName, Price, Manfacturer) Input Schema Output Schema

M.P. Johnson, DBMS, Stern/NYU, Sp R.A.  SQL R.A. Projection   SQL SELECT R.A. Selection   SQL WHERE R.A. Join  SQL FROM  Comma-separated list… What goes in the WHERE clause: x = y, x < y, x <= y, etc.  For number, they have the usual meanings  For CHAR and VARCHAR: lexicographic ordering Expected conversion between CHAR and VARCHAR  For dates and times, what you expect

M.P. Johnson, DBMS, Stern/NYU, Sp R.A.  SQL Movies(Title,Year,Length,inColor,Studio,Prdcr#) Q: How long was Star Wars (1977), in R.A.? Q: In SQL? Q: Which Fox movies are are at least 100 minutes long, in R.A.? Q: In SQL?

M.P. Johnson, DBMS, Stern/NYU, Sp R.A.  SQL Reps(ssn, name, etc.) Clients(ssn, name, rssn) Q: Who are George’s clients, in R.A.? Second answer from last time:   Clients.name (  Reps.name=“George” and Reps.ssn=rssn (Reps x Clients)) In SQL?

M.P. Johnson, DBMS, Stern/NYU, Sp The LIKE operator s LIKE p: pattern matching on strings p may contain two special symbols:  _ = any single character  % = zero or more chars Product(Name, Price, Category, Manufacturer) Find all products whose name contains ‘gizmo’: SELECT * FROM Products WHERE PName LIKE ‘%gizmo%’

M.P. Johnson, DBMS, Stern/NYU, Sp The LIKE operator Q: What it want to search for values containing a ‘%’? PName LIKE ‘%%’ won’t work Instead, must use escape chars In C/C++/J, prepend ‘\’ In SQL, prepend an arbitrary escape char: PName LIKE ‘x%x%’ ESCAPE ‘x’

M.P. Johnson, DBMS, Stern/NYU, Sp Eliminating Duplicates SELECT DISTINCT category FROM Product SELECT DISTINCT category FROM Product Compare to: SELECT category FROM Product SELECT category FROM Product Category Gadgets Photography Household Category Gadgets Photography Household

M.P. Johnson, DBMS, Stern/NYU, Sp Ordering the Results Ordering is ascending, unless you specify the DESC keyword per attribute. SELECT pname, price, manufacturer FROM Product WHERE category=‘gizmo’ AND price > 50 ORDER BY price, pname SELECT pname, price, manufacturer FROM Product WHERE category=‘gizmo’ AND price > 50 ORDER BY price, pname SELECT pname, price, manufacturer FROM Product WHERE category=‘gizmo’ AND price > 50 ORDER BY price DESC, pname ASC SELECT pname, price, manufacturer FROM Product WHERE category=‘gizmo’ AND price > 50 ORDER BY price DESC, pname ASC

M.P. Johnson, DBMS, Stern/NYU, Sp Ordering the Results SELECTCategory FROMProduct ORDER BYPName SELECTCategory FROMProduct ORDER BYPName PNamePriceCategoryManufacturer Gizmo$19.99GadgetsGizmoWorks Powergizmo$29.99GadgetsGizmoWorks SingleTouch$149.99PhotographyCanon MultiTouch$203.99HouseholdHitachi ?

M.P. Johnson, DBMS, Stern/NYU, Sp Ordering the Results SELECT DISTINCT category FROMProduct ORDER BYcategory SELECT DISTINCT category FROMProduct ORDER BYcategory Compare to: Category Gadgets Household Photography SELECT DISTINCT category FROMProduct ORDER BYPName SELECT DISTINCT category FROMProduct ORDER BYPName ?

M.P. Johnson, DBMS, Stern/NYU, Sp Joins in SQL (6.2) Connect two or more tables: PNamePriceCategoryManufacturer Gizmo$19.99GadgetsGizmoWorks Powergizmo$29.99GadgetsGizmoWorks SingleTouch$149.99PhotographyCanon MultiTouch$203.99HouseholdHitachi Product Company CNameStockPriceCountry GizmoWorks25USA Canon65Japan Hitachi15Japan What is the connection between them?

M.P. Johnson, DBMS, Stern/NYU, Sp Joins in SQL Product (pname, price, category, manufacturer) Company (cname, stockPrice, country) Find all products under $200 manufactured in Japan; return their names and prices. SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200 Join between Product and Company

M.P. Johnson, DBMS, Stern/NYU, Sp Joins in SQL PNamePriceCategoryManufacturer Gizmo$19.99GadgetsGizmoWorks Powergizmo$29.99GadgetsGizmoWorks SingleTouch$149.99PhotographyCanon MultiTouch$203.99HouseholdHitachi Product Company CnameStockPriceCountry GizmoWorks25USA Canon65Japan Hitachi15Japan PNamePrice SingleTouch$ SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200

M.P. Johnson, DBMS, Stern/NYU, Sp Joins in SQL Product (pname, price, category, manufacturer) Company (cname, stockPrice, country) Find all countries that manufacture some product in the ‘Gadgets’ category. SELECTCountry FROMProduct, Company WHEREManufacturer=CName AND Category=‘Gadgets’

M.P. Johnson, DBMS, Stern/NYU, Sp Joins in SQL NamePriceCategoryManufacturer Gizmo$19.99GadgetsGizmoWorks Powergizmo$29.99GadgetsGizmoWorks SingleTouch$149.99PhotographyCanon MultiTouch$203.99HouseholdHitachi Product Company CnameStockPriceCountry GizmoWorks25USA Canon65Japan Hitachi15Japan Country ?? What is the problem? What’s the solution? SELECT Country FROM Product, Company WHERE Manufacturer=CName AND Category=‘Gadgets’

M.P. Johnson, DBMS, Stern/NYU, Sp Joins Product (pname, price, category, manufacturer) Purchase (buyer, seller, store, product) Person(name, phone, city) Find names of Seattleites who bought Gadgets, and the names of the stores they bought such product from. SELECT DISTINCT name, store FROM Person, Purchase, Product WHERE persname=buyer AND product = pname AND city=‘Seattle’ AND category=‘Gadgets’

M.P. Johnson, DBMS, Stern/NYU, Sp Disambiguating Attributes Sometimes two relations have the same attr: Person(pname, address, worksfor) Company(cname, address) SELECT DISTINCT pname, address FROM Person, Company WHERE worksfor = cname SELECT DISTINCT Person.pname, Company.address FROM Person, Company WHERE Person.worksfor = Company.cname Which address ?

M.P. Johnson, DBMS, Stern/NYU, Sp Tuple Variables SELECT DISTINCT x.store FROM Purchase AS x, Purchase AS y WHERE x.product = y.product AND y.store = ‘BestBuy’ SELECT DISTINCT x.store FROM Purchase AS x, Purchase AS y WHERE x.product = y.product AND y.store = ‘BestBuy’ Find all stores that sold at least one product that the store ‘BestBuy’ also sold: Answer (store) Product (pname, price, category, manufacturer) Purchase (buyer, seller, store, product) Person(persname, phoneNumber, city)

M.P. Johnson, DBMS, Stern/NYU, Sp Tuple Variables Tuple variables introduced automatically: Product ( name, price, category, manufacturer) Becomes: Doesn’t work when Product occurs more than once In that case the user needs to define variables explicitly SELECT name FROM Product WHERE price > 100 SELECT name FROM Product WHERE price > 100 SELECT Product.name FROM Product AS Product WHERE Product.price > 100 SELECT Product.name FROM Product AS Product WHERE Product.price > 100

M.P. Johnson, DBMS, Stern/NYU, Sp SQL Query Semantics 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  {(a1,…,ak)} return Answer Answer = {} for x1 in R1 do for x2 in R2 do ….. for xn in Rn do if Conditions then Answer = Answer  {(a1,…,ak)} return Answer

M.P. Johnson, DBMS, Stern/NYU, Sp SQL Query Semantics SELECT a1, a2, …, ak FROM R1 AS x1, R2 AS x2, …, Rn AS xn WHERE Conditions 2. Parallel assignment Doesn’t impose any order! Answer = {} for all assignments x1 in R1, …, xn in Rn do if Conditions then Answer = Answer  {(a1,…,ak)} return Answer Answer = {} for all assignments x1 in R1, …, xn in Rn do if Conditions then Answer = Answer  {(a1,…,ak)} return Answer

M.P. Johnson, DBMS, Stern/NYU, Sp First Unintuitive SQLism SELECTR.A FROMR, S, T WHERER.A=S.A OR R.A=T.A Looking for R  (S  T) But what happens if T is empty? See transcript of this in Oracle on salestranscript