Matthew P. Johnson, OCL5, CISDD CUNY, Sept 20051 OCL4 Oracle 10g: SQL & PL/SQL Session #2 Matthew P. Johnson CISDD, CUNY June, 2005.

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.
Chapter 3 Notes. 3.1 Functional Dependencies A functional dependency is a statement that – two tuples of a relation that agree on some particular set.
Relational Algebra (end) SQL April 19 th, Complex Queries Product ( pid, name, price, category, maker-cid) Purchase (buyer-ssn, seller-ssn, store,
Lecture 6: Design Constraints and Functional Dependencies January 21st, 2004.
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.
Database Systems Lecture #5 Yan Pan School of Software, SYSU 2011.
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 227 Database Systems I Design Theory for Relational Databases.
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.
Functional Dependencies Definition: If two tuples agree on the attributes A, A, … A 12n then they must also agree on the attributes B, B, … B 12m Formally:
1 Introduction to Database Systems CSE 444 Lectures 8 & 9 Database Design April 16 & 18, 2008.
Matthew P. Johnson, OCL2, CISDD CUNY, January OCL2 Oracle 10g: SQL & PL/SQL Session #3 Matthew P. Johnson CISDD, CUNY January, 2005.
Lecture #3 Functional Dependencies Normalization Relational Algebra Thursday, October 12, 2000.
The principal problem that we encounter is redundancy, where a fact is repeated in more than one tuple. Most common cause: attempts to group into one relation.
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.
M.P. Johnson, DBMS, Stern/NYU, Spring C : Database Management Systems Lecture #9 Matthew P. Johnson Stern School of Business, NYU Spring, 2005.
M.P. Johnson, DBMS, Stern/NYU, Sp20041 C : Database Management Systems Lecture #10 Matthew P. Johnson Stern School of Business, NYU Spring, 2004.
1 Functional Dependency and Normalization Informal design guidelines for relation schemas. Functional dependencies. Normal forms. Normalization.
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 #7 Matthew P. Johnson Stern School of Business, NYU Spring,
M.P. Johnson, DBMS, Stern/NYU, Spring C : Database Management Systems Lecture #5 M.P. Johnson Stern School of Business, NYU Spring, 2008.
Boyce-Codd NF & Lossless Decomposition Professor Sin-Min Lee.
M.P. Johnson, DBMS, Stern/NYU, Sp20041 C : Database Management Systems Lecture #6 Matthew P. Johnson Stern School of Business, NYU Spring, 2004.
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.
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.
Functional Dependencies and Relational Schema Design.
1. Midterm summary Types of data on the web: unstructured, semi- structured, structured Scale and uncertainty are key features Main goals are to model,
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.
CS143 Review: Normalization Theory Q: Is it a good table design? We can start with an ER diagram or with a large relation that contain a sample of the.
Lecture 09: Functional Dependencies. Outline Functional dependencies (3.4) Rules about FDs (3.5) Design of a Relational schema (3.6)
SQL. SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: ANSI SQL, SQL92 (a.k.a.
Functional Dependencies. Outline Functional dependencies (3.4) Rules about FDs (3.5) Design of a Relational schema (3.6)
1 Lecture 7: Normal Forms, Relational Algebra Monday, 10/15/2001.
© D. Wong Normalization  Purpose: process to eliminate redundancy in relations due to functional or multi-valued dependencies.  Decompose relation.
1 Lecture 10: Database Design Wednesday, January 26, 2005.
Functional Dependencies and Relational Schema Design.
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 10: Database Design and Relational Algebra Monday, October 20, 2003.
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.
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.
CS411 Database Systems Kazuhiro Minami 04: Relational Schema Design.
1 Lecture 9: Database Design Wednesday, January 25, 2006.
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,
Formal definition of a key A key is a set of attributes A 1,..., A n such that for any other attribute B: A 1,..., A n  B A minimal key is a set of attributes.
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),
Lecture 11: Functional Dependencies
SQL.
Server-Side Application and Data Management IT IS 3105 (FALL 2009)
Introduction to SQL Wenhao Zhang October 5, 2018.
Functional Dependencies and Relational Schema Design
SQL Introduction Standard language for querying and manipulating data
Lecture 8: Database Design
Lectures 3: Introduction to SQL 2
Introduction to Database Systems CSE 444 Lecture 02: SQL
OCL3 Oracle 10g: SQL & PL/SQL Session #3
Lecture 6: Functional Dependencies
Lecture 11: Functional Dependencies
Lecture 09: Functional Dependencies
Presentation transcript:

Matthew P. Johnson, OCL5, CISDD CUNY, Sept OCL4 Oracle 10g: SQL & PL/SQL Session #2 Matthew P. Johnson CISDD, CUNY June, 2005

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Agenda Last time: FDs This time: 1. Anomalies 2. Normalization Then: SQL

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Review examples: finding FDs Product(name, price, category, color) name, category  price category  color Keys are: {name, category} Enrollment(student, address, course, room, time) student  address room, time  course student, course  room, time Keys are: [in class]

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Next topic: Anomalies Identify anomalies in existing schema How to decompose a relation Boyce-Codd Normal Form (BCNF) Recovering information from a decomposition Third Normal Form

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Types of anomalies Redundancy  Repeat info unnecessarily in several tuples Update anomalies:  Change info in one tuple but not in another Deletion anomalies:  Delete some values & lose other values too Insert anomalies:  Inserting row means having to insert other, separate info / null-ing it out

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Example of anomalies Redundancy: name, maddress Update anomaly: Bill moves Delete anom.: Bill doesn’t pay bills, lose phones  lose Bill! Insert anom: can’t insert someone without a (non-null) phone Underlying cause: SSN-phone is many-many Effect: partial dependency ssn  name, maddress,  Whereas key = {ssn,phone} NameSSNMailing-addressPhone Michael123NY Michael123NY Hilary456DC Hilary456DC Bill789Chappaqua Bill789Chappaqua SSN  Name, Mailing-address SSN  Phone

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Decomposition by projection Soln: replace anomalous R with projections of R onto two subsets of attributes Projection: an operation in Relational Algebra  Corresponds to SELECT command in SQL Projecting R onto attributes (A 1,…,A n ) means removing all other attributes  Result of projection is another relation  Yields tuples whose fields are A 1,…,A n  Resulting duplicates ignored

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Projection for decomposition R 1 = projection of R on A 1,..., A n, B 1,..., B m R 2 = projection of R on A 1,..., A n, C 1,..., C p A 1,..., A n  B 1,..., B m  C 1,..., C p = all attributes, usually disjoint sets R 1 and R 2 may (/not) be reassembled to produce original R R(A 1,..., A n, B 1,..., B m, C 1,..., C p ) R 1 (A 1,..., A n, B 1,..., B m ) R 2 (A 1,..., A n, C 1,..., C p )

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Chappaqua789Bill DC456Hilary NY123Michael Mailing-addressSSNName Decomposition example The anomalies are gone  No more redundant data  Easy to for Bill to move  Okay for Bill to lose all phones Break the relation into two: NameSSNMailing-addressPhone Michael123NY Michael123NY Hilary456DC Hilary456DC Bill789Chappaqua Bill789Chappaqua PhoneSSN

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Thus: high-level strategy Person buys Product name pricenamessn Conceptual Model: Relational Model: plus FD’s Normalization: Eliminates anomalies

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Using FDs to produce good schemas 1. Start with set of relations 2. Define FDs (and keys) for them based on real world 3. Transform your relations to “normal form” (normalize them)  Do this using “decomposition” Intuitively, good design means  No anomalies  Can reconstruct all (and only the) original information

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Decomposition terminology Projection: eliminating certain attributes from relation Decomposition: separating a relation into two by projection Join: (re)assembling two relations  Whenever a row from R 1 and a row from R 2 have the same value for some atts A, join together to form a row of R 3 If exactly the original rows are reproduced by joining the relations, then the decomposition was lossless  We join on the attributes R 1 and R 2 have in common (As) If it can’t, the decomposition was lossy

Matthew P. Johnson, OCL5, CISDD CUNY, Sept A decomposition is lossless if we can recover: R(A,B,C) R1(B,C) R2(B,A) R’(A,B,C) should be the same as R(A,B,C) R’ is in general larger than R. Must ensure R’ = R Decompose Recover Lossless Decompositions

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Lossless decomposition Sometimes the data can be reproduced: (Word, 100) + (Word, WP)  (Word, 100, WP) (Oracle, 1000) + (Oracle, DB)  (Oracle, 1000, DB) (Access, 100) + (Access, DB)  (Access, 100, DB) NamePriceCategory Word100WP Oracle1000DB Access100DB NamePrice Word100 Oracle1000 Access100 NameCategory WordWP OracleDB AccessDB

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Lossy decomposition Sometimes it’s not: (Word, WP) + (100, WP)  (Word, 100, WP) (Oracle, DB) + (1000, DB)  (Oracle, 1000, DB) (Oracle, DB) + (100, DB)  (Oracle, 100, DB) (Access, DB) + (1000, DB)  (Access, 1000, DB) (Access, DB) + (100, DB)  (Access, 100, DB) NamePriceCategory Word100WP Oracle1000DB Access100DB NameCategory WordWP OracleDB AccessDB PriceCategory 100WP 1000DB 100DB What’s wrong?

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Ensuring lossless decomposition Examples: name  price, so first decomposition was lossless category  name and category  price, and so second decomposition was lossy R(A 1,..., A n, B 1,..., B m, C 1,..., C p ) If A 1,..., A n  B 1,..., B m or A 1,..., A n  C 1,..., C p Then the decomposition is lossless R 1 (A 1,..., A n, B 1,..., B m ) R 2 (A 1,..., A n, C 1,..., C p ) Note: don’t need both

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Quick lossless/lossy example At a glance: can we decompose into R 1 (Y,X), R 2 (Y,Z)? At a glance: can we decompose into R 1 (X,Y), R 2 (X,Z)? XYZ

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Normal Forms First Normal Form = all attributes are atomic  As opposed to set-valued  Assumed all along Second Normal Form (2NF) Third Normal Form (3NF) Boyce Codd Normal Form (BCNF) Fourth Normal Form (4NF) Fifth Normal Form (5NF)

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Most important: BCNF A simple condition for removing anomalies from relations: I.e.: The left side must always contain a key I.e: If a set of attributes determines other attributes, it must determine all the attributes A relation R is in BCNF if: If As  Bs is a non-trivial dependency in R, then As is a superkey for R A relation R is in BCNF if: If As  Bs is a non-trivial dependency in R, then As is a superkey for R Codd: Ted Codd, IBM researcher, inventor of relational model, 1970 Boyce: Ray Boyce, IBM researcher, helped develop SQL in the 1970s

Matthew P. Johnson, OCL5, CISDD CUNY, Sept BCNF decomposition algorithm Repeat choose A 1, …, A m  B 1, …, B n that violates the BNCF condition //Heuristic: choose Bs as large as possible split R into R 1 (A 1, …, A m, B 1, …, B n ) and R 2 (A 1, …, A m, [others]) continue with both R 1 and R 2 Until no more violations Repeat choose A 1, …, A m  B 1, …, B n that violates the BNCF condition //Heuristic: choose Bs as large as possible split R into R 1 (A 1, …, A m, B 1, …, B n ) and R 2 (A 1, …, A m, [others]) continue with both R 1 and R 2 Until no more violations A’s Others B’s R1R1 R2R2

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Boyce-Codd Normal Form Name/phone example is not BCNF:  {ssn,phone} is key  FD: ssn  name,mailing-address holds Violates BCNF: ssn is not a superkey Its decomposition is BCNF  Only superkeys  anything else NameSSNMailing-addressPhone Michael123NY Michael123NY NameSSNMailing-address Michael123NY SSNPhoneNumber

Matthew P. Johnson, OCL5, CISDD CUNY, Sept BCNF motivation Two big ideas:  Only a key field can determine other fields  Key values are unique   no FD-caused redundancy Slogan: “Every FD must contain the key, the whole key and nothing but the key.” More accurate: “Every FD must contain (on the left) a key, a whole key, and maybe other fields.

Matthew P. Johnson, OCL5, CISDD CUNY, Sept BCNF Decomposition Larger example: multiple decompositions {Title, Year, Studio, President, Pres-Address} FDs:  Title Year  Studio  Studio  President  President  Pres-Address   Studio  President, Pres-Address (why?) No many-many this time Problem cause: transitive FDs:  Title,year  studio  president

Matthew P. Johnson, OCL5, CISDD CUNY, Sept BCNF Decomposition Illegal: As  Bs, where As don’t include key Decompose: Studio  President, Pres-Address  As = {studio}  Bs = {president, pres-address}  Cs = {title, year} Result: 1. Studios(studio, president, pres-address) 2. Movies(studio, title, year) Is (2) in BCNF? Is in (1) BCNF?  Key: Studio  FD: President  Pres-Address  Q: Does president  studio? If so, president is a key  But if not, it violates BCNF

Matthew P. Johnson, OCL5, CISDD CUNY, Sept BCNF Decomposition Studios(studio, president, pres-address) Illegal: As  Bs, where As don’t include key  Decompose: President  Pres-Address  As = {president}  Bs = {pres-address}  Cs = {studio} {Studio, President, Pres-Address} becomes  {President, Pres-Address}  {Studio, President}

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Roadmap Want to remove redundancy/anomalies  Convert to BCNF Find FDs – closure alg Check if each FD A  B is ok  If A contains a key If not, decompose into R1(A,B), R2(A,rest) Because A  B, this will be lossless Could check by joining R1 and R2  Would get no rows not in original

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Decomposition algorithm example R(N,O,R,P) F = {N  O, O  R, R  N} Key: N,P Violations of BCNF: N  O, O  R, N  OR  which kinds of violations are these? Pick N  OR(on board) Can we rejoin?(on board) What happens if we pick N  O instead? Can we rejoin? (on board) NameOfficeResidencePhone GeorgePres.WH202-… GeorgePres.WH486-… DickVPNO202-… DickVPNO307-…

Matthew P. Johnson, OCL5, CISDD CUNY, Sept BCNF summary BCNF decomposition is lossless  Can reproduce original by joining Saw last time: Every 2-attribute relation is in BCNF Final set of decomposed relations might be different depending on  Order of bad FDs chosen Saw last time: But all results will be in BCNF

Matthew P. Johnson, OCL5, CISDD CUNY, Sept BCNF summary BCNF decomp. does not lose data  Resulting relations can be rejoined to obtain the original In BCNF, there’s no FD-based redundancy  Values in key field are unique  Other FDs are from key fields   everything is “as compressed as possible”

Matthew P. Johnson, OCL5, CISDD CUNY, Sept BCNF Review Q: What’s required for BCNF? Q: What’s the slogan for BCNF? Q: Who are B & C?

Matthew P. Johnson, OCL5, CISDD CUNY, Sept BCNF Review Q: How do we fix a non-BCNF relation? Q: If As  Bs violates BCNF, what do we do?  Q: In this case, could the decomposition be lossy? Q: Under what circumstances could a decomposition be lossy? Q: How do we combine two relations?

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Design Goals Goal for a relational database design is:  No redundancy  Lossless Join  Dependency Preservation If we cannot achieve this, we accept one of  dependency loss  use of more expensive inter-relational methods to preserve dependencies  data redundancy due to use of 3NF Interesting: SQL does not provide a direct way of specifying FDs other than superkeys  can specify FDs using assertions, but they are expensive to test

Matthew P. Johnson, OCL5, CISDD CUNY, Sept 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 Next:  Create, update, query tables with R.A/SQL  Write SQL/DB-connected applications

Matthew P. Johnson, OCL5, CISDD CUNY, Sept High-level agenda Install Oracle Start SQL Lab on Oracle system info/SQL

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Next topic: SQL 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 Oracle’s version 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)

Matthew P. Johnson, OCL5, CISDD CUNY, Sept 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

Matthew P. Johnson, OCL5, CISDD CUNY, Sept “Tables” PNamePriceCategoryManufacturer Gizmo$19.99GadgetsGizmoWorks Powergizmo$29.99GadgetsGizmoWorks SingleTouch$149.99PhotographyCanon MultiTouch$203.99HouseholdHitachi Product Attribute names Table name Tuples or rows

Matthew P. Johnson, OCL5, CISDD CUNY, Sept 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”

Matthew P. Johnson, OCL5, CISDD CUNY, Sept 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”

Matthew P. Johnson, OCL5, CISDD CUNY, Sept A Notation for SQL Queries SELECT Name, Price, Manufacturer FROM Product WHERE Price > 100 Product(PName, Price, Category, Manfacturer) (PName, Price, Manfacturer) Input Schema Output Schema

Matthew P. Johnson, OCL5, CISDD CUNY, Sept SQL SQL SELECT  Sometimes called a “projection” 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

Matthew P. Johnson, OCL5, CISDD CUNY, Sept SQL e.g. Movies(Title,Year,Length,inColor,Studio,Prdcr#) Q: How long was Star Wars (1977), in SQL? Q: Which Fox movies are are at least 100 minutes long, in SQL?

Matthew P. Johnson, OCL5, CISDD CUNY, Sept SQL e.g. Reps(ssn, name, etc.) Clients(ssn, name, rssn) Q: Who are George’s clients, in SQL? Conceptually:   Clients.name (  Reps.name=“George” and Reps.ssn=rssn (Reps x Clients))

Matthew P. Johnson, OCL5, CISDD CUNY, Sept 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 Name LIKE '%gizmo%'

Matthew P. Johnson, OCL5, CISDD CUNY, Sept 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%' ESCAPE 'x'

Matthew P. Johnson, OCL5, CISDD CUNY, Sept More on escape chars SQL: no official default escape char In SQL*Plus: default escape char == '\'  Can set with  SQL> set escape x Other tools, DBMSs: your mileage may vary SQL string literals put in ' ':  'mystring' Single-quote literals escaped with single- quotes:  'George''s string'

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Q: What about double quotes? A: Can’t be used in place of single quotes But can be used when Oracle would otherwise misparse your command, e.g.: 1. Names with spaces:  create table bad table name (a int, b int); 2. Reserved words as names:  create table badfieldname(from int, b int);

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Q: Can an escape char be an escape string? A: No. SQL> select * from newtable where a like '%\%' escape '\'; A B h%i there SQL> select * from newtable where a like '%\%' escape '\\'; select * from newtable where a like '%\%' escape '\\' * ERROR at line 1: ORA-01425: escape character must be character string of length 1 SQL> select * from newtable where a like '%\%' escape '\'; A B h%i there SQL> select * from newtable where a like '%\%' escape '\\'; select * from newtable where a like '%\%' escape '\\' * ERROR at line 1: ORA-01425: escape character must be character string of length 1

Matthew P. Johnson, OCL5, CISDD CUNY, Sept More on single-quotes Dates with DATE:  DATE ' ' Timestamps with TIMESTAMP:  TIMESTAMP ' :00:00'

Matthew P. Johnson, OCL5, CISDD CUNY, Sept 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

Matthew P. Johnson, OCL5, CISDD CUNY, Sept 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

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Ordering the Results SELECT Category FROM Product ORDER BY PName SELECT Category FROM Product ORDER BY PName PNamePriceCategoryManufacturer Gizmo$19.99GadgetsGizmoWorks Powergizmo$29.99GadgetsGizmoWorks SingleTouch$149.99PhotographyCanon MultiTouch$203.99HouseholdHitachi ?

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Joins in SQL 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?

Matthew P. Johnson, OCL5, CISDD CUNY, Sept 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

Matthew P. Johnson, OCL5, CISDD CUNY, Sept 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

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Joins in SQL 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'

Matthew P. Johnson, OCL5, CISDD CUNY, Sept 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'

Matthew P. Johnson, OCL5, CISDD CUNY, Sept 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'

Matthew P. Johnson, OCL5, CISDD CUNY, Sept 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 ?

Matthew P. Johnson, OCL5, CISDD CUNY, Sept 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)

Matthew P. Johnson, OCL5, CISDD CUNY, Sept 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

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Details: Disambiguation in SQL Every selected field must be unambiguous For R(A,B),  Select A from R, R   Select R1.A from R R1, R R2 Consider: Why? * is shorthand for all fields, each must be unambiguous  Select * from R R1, R R2 SQL> Select * from R, R; Select * from R, R * ERROR at line 1: ORA-00918: column ambiguously defined SQL> Select * from R, R; Select * from R, R * ERROR at line 1: ORA-00918: column ambiguously defined

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Details: Disambiguation in Oracle SQL Can rename fields by  Select name as n …  Select name n … But not by  Select name=n… Can rename relations only by  … from tab t1, tab t2 Lesson: if you get errors, remove all =s, ASs

Matthew P. Johnson, OCL5, CISDD CUNY, Sept 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

Matthew P. Johnson, OCL5, CISDD CUNY, Sept 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

Matthew P. Johnson, OCL5, CISDD CUNY, Sept Now lab 2 online