Intro. to SQL DSC340 Mike Pangburn. Learning Objectives Understand the data-representation terminology underlying relational databases Understand core.

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 - Subqueries and Schema Chapter 3.4 V3.0 Napier University Dr Gordon Russell.
SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: SQL92, SQL2, SQL3. Vendors support.
SQL – JOINs and VIEWs Chapter 3.3 V3.0 Napier University Dr Gordon Russell.
Relational Algebra, Join and QBE Yong Choi School of Business CSUB, Bakersfield.
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.
M.P. Johnson, DBMS, Stern/NYU, Spring C : Database Management Systems Lecture #10 Matthew P. Johnson Stern School of Business, NYU Spring,
1 Lecture 03: SQL Friday, January 7, Administrivia Have you logged in IISQLSRV yet ? HAVE YOU CHANGED YOUR PASSWORD ? Homework 1 is now posted.
M.P. Johnson, DBMS, Stern/NYU, Spring C : Database Management Systems Lecture #7 M.P. Johnson Stern School of Business, NYU Spring, 2008.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 8 Advanced SQL.
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.
M.P. Johnson, DBMS, Stern/NYU, Sp20041 C : Database Management Systems Lecture #10 Matthew P. Johnson Stern School of Business, NYU Spring, 2004.
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.
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)
CSE544: SQL Monday 3/27 and Wednesday 3/29, 2006.
+ From Relational Algebra to SQL W2013 CSCI 2141.
1. Midterm summary Types of data on the web: unstructured, semi- structured, structured Scale and uncertainty are key features Main goals are to model,
Chapter 3 Single-Table Queries
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 The Relational Database Model. 2 Learning Objectives Terminology of relational model. How tables are used to represent data. Connection between mathematical.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
9/7/2012ISC329 Isabelle Bichindaritz1 The Relational Database Model.
Lectures 2&3: Introduction to SQL. Lecture 2: SQL Part I Lecture 2.
JOI/1 Data Manipulation - Joins Objectives –To learn how to join several tables together to produce output Contents –Extending a Select to retrieve data.
SQL SQL Review. SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: ANSI SQL, SQL92.
NULLs & Outer Joins Objectives of the Lecture : To consider the use of NULLs in SQL. To consider Outer Join Operations, and their implementation in SQL.
1 Database & DBMS The data that goes into transaction processing systems (TPS), also goes to a database to be stored and processed later by decision support.
Database Management COP4540, SCS, FIU Structured Query Language (Chapter 8)
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.
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
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.
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.
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 5: SQL I Rob Gleasure robgleasure.com.
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.
Relational Model By Dr.S.Sridhar, Ph.D.(JNUD), RACI(Paris, NICE), RMR(USA), RZFM(Germany)
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
Cse 344 January 12th –joins.
COMP 430 Intro. to Database Systems
March 30th – intro to joins
Cse 344 January 10th –joins.
Introduction to SQL Wenhao Zhang October 5, 2018.
CSE544 SQL Wednesday, March 31, 2004.
SQL Introduction Standard language for querying and manipulating data
Lectures 3: Introduction to SQL 2
Introduction to Database Systems CSE 444 Lecture 02: SQL
Terminology Product Attribute names Name Price Category Manufacturer
Lectures 2: Introduction to SQL 1
Syllabus Introduction Website Management Systems
Presentation transcript:

Intro. to SQL DSC340 Mike Pangburn

Learning Objectives Understand the data-representation terminology underlying relational databases Understand core SQL concepts that stem from relational algebra cover all the fundamental operators other than divide Gain familiarity with SQL syntax 2

Relational Databases and Tables  A Relational Database is a database management system (DBMS) that holds a set of tables, like Excel worksheets, each filled with data  A table = a set of rows or “records”  Like a list…  …but rows have no assumed order  Even columns have no assumed order

A sample database table PNamePriceCategoryManufacturer Gizmo$19.99GadgetsGizmoWorks Powergizmo$29.99GadgetsGizmoWorks SingleTouch$149.99PhotographyCanon MultiTouch$203.99HouseholdHitachi Product Attribute names Table name Tuples or rows

DB Terminology overview TermDefinition Relation (also, Entity)A table. Tuple, (also, record or “entity instance”) A row. Attribute (also, field)A column. Attribute valueThe value in a particular table cell (i.e., a row/column intersection). Primary keySpecified column(s) providing a unique value for every row. Table schemeThe set of attributes (not their values) defining the structure of a table. Database schemaThe full set of named tables and their schemes, in the full database (which could contain many tables).

SQL – what is it?  All SQL query take some rectangular input table(s) and, using that data as you nicely ask it to, generates your desirable output table  You must ask nicely, i.e., properly  A simple language  Not a true programming language  Much easier to learn  Still very hard to master  Why was SQL developed?  As a user-friendly means to define and manipulating data in relational databases  Incredibly valuable for addressing managerial ad hoc query questions 6

SQL Query Basic form: SELECT attributes FROM table (or multiple tables, often “joined”) WHERE conditions (“row restrictions”) SELECT attributes FROM table (or multiple tables, often “joined”) WHERE conditions (“row restrictions”)

1-table query with row filtering 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 “row restriction”

A query projecting specific columns 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 “row restriction” with certain columns “projected”

Selections What goes in the WHERE clause:  x = y, x < y, x <= y, etc  For numbers, they have the usual meanings  For characters: lexicographic ordering  For dates and times, earlier is less than later  Pattern matching on strings: s LIKE p (next slide)  You can combine selections using AND / OR type logic  E.g., WHERE x z)

The LIKE operator  s LIKE p: pattern matching on strings  p may contain two special “wildcard” symbols:  % = any sequence of characters  _ = any single character  Note: these two special characters are system dependent… “Google” the LIKE wildcard symbols for any system you use Product(Name, Price, Category, Manufacturer) Find all products whose name mentions ‘gizmo’: SELECT * FROM Products WHERE PName LIKE ‘%gizmo%’

Hoe to eliminate identical output rows? Compare to: SELECT DISTINCT category FROM Product SELECT DISTINCT category FROM Product Household Photography Gadgets Category SELECT category FROM Product SELECT category FROM Product Household Photography Gadgets Category

Ordering the Results SELECT pname, price, manufacturer FROM Product WHERE category=‘Gadgets’ AND price > 50 ORDER BY price, pname SELECT pname, price, manufacturer FROM Product WHERE category=‘Gadgets’ AND price > 50 ORDER BY price, pname Ordering is ascending, unless you specify ORDER BY DESC (DESC means you want descending order) Ties are broken by the second attribute on the ORDER BY list, etc.

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 ?

“Joining tables” 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? Do you think the DBMS sees that?

Joins using 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

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 Joins using SQL

Joins and unexpected “duplicated” results Example: Find all countries that manufacture some product in the ‘Gadgets’ category Product (pname, price, category, manufacturer) Company (cname, stockPrice, country). SELECT Country FROM Product, Company WHERE Manufacturer=CName AND Category=‘Gadgets’

Joins in SQL PNamePriceCategoryManufacturer Gizmo$19.99GadgetsGizmoWorks Powergizmo$29.99GadgetsGizmoWorks SingleTouch$149.99PhotographyCanon MultiTouch$203.99HouseholdHitachi Product Company CnameStockPriceCountry GizmoWorks25USA Canon65Japan Hitachi15Japan Country ?? What will the two output lines be?Do we recall how to avoid showing identical output rows? SELECT Country FROM Product, Company WHERE Manufacturer=CName AND Category=‘Gadgets’

An example joining 3 tables 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’

Disambiguating Attributes  Sometimes two relations have same attribute 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 ?

Renaming Columns PNamePriceCategoryManufacturer Gizmo$19.99GadgetsGizmoWorks Powergizmo$29.99GadgetsGizmoWorks SingleTouch$149.99PhotographyCanon MultiTouch$203.99HouseholdHitachi SELECT Pname AS prodName, Price AS askPrice FROM Product WHERE Price > 100 Product prodNameaskPrice SingleTouch$ MultiTouch$ Query with renaming

“Appendix:” More detail on Join operations  Consider two new tables: Car and Driver  Let’s now look in detail at what happens “behind the scenes” when you ask a Database Management System (a DBMS) to join the two tables Reference: car and driver table examples from

Two tables for our example SELECT * from driver; NAMEDOB Jim Smith11 Jan 1980 Bob Smith23 Mar 1981 Bob Jones3 Dec 1986 REGNOMAKECOLOURPRICEOWNER F611 AAAFORDRED12000Jim Smith J111 BBBSKODABLUE11000Jim Smith A155 BDEMERCEDESBLUE22000Bob Smith K555 GHTFIATGREEN6000Bob Jones SC04 BFESMARTBLUE13000 SELECT * from car;

REGNOMAKECOLOURPRICEOWNERNAMEDOB F611 AAAFORDRED12000Jim Smith 11 Jan 1980 J111 BBBSKODABLUE11000Jim Smith 11 Jan 1980 A155 BDEMERCEDESBLUE22000Bob SmithJim Smith11 Jan 1980 K555 GHTFIATGREEN6000Bob JonesJim Smith11 Jan 1980 SC04 BFESMARTBLUE13000Jim Smith11 Jan 1980 F611 AAAFORDRED12000Jim SmithBob Smith23 Mar 1981 J111 BBBSKODABLUE11000Jim SmithBob Smith23 Mar 1981 A155 BDEMERCEDESBLUE22000Bob Smith 23 Mar 1981 K555 GHTFIATGREEN6000Bob JonesBob Smith23 Mar 1981 SC04 BFESMARTBLUE13000Bob Smith23 Mar 1981 F611 AAAFORDRED12000Jim SmithBob Jones3 Dec 1986 J111 BBBSKODABLUE11000Jim SmithBob Jones3 Dec 1986 A155 BDEMERCEDESBLUE22000Bob SmithBob Jones3 Dec 1986 K555 GHTFIATGREEN6000Bob Jones 3 Dec 1986 SC04 BFESMARTBLUE13000Bob Jones3 Dec 1986  The following SQL is missing the join condition for the two tables  SELECT * FROM car,driver  What does it do? It takes all combinations of rows from the two tables. What if you forget the “join condition?”

Adding the Join condition REGNOMAKECOLOURPRICEOWNERNAMEDOB F611 AAAFORDRED12000Jim Smith 11 Jan 1980 J111 BBBSKODABLUE11000Jim Smith 11 Jan 1980 A155 BDEMERCEDESBLUE22000Bob SmithJim Smith11 Jan 1980 K555 GHTFIATGREEN6000Bob JonesJim Smith11 Jan 1980 SC04 BFESMARTBLUE13000Jim Smith11 Jan 1980 F611 AAAFORDRED12000Jim SmithBob Smith23 Mar 1981 J111 BBBSKODABLUE11000Jim SmithBob Smith23 Mar 1981 A155 BDEMERCEDESBLUE22000Bob Smith 23 Mar 1981 K555 GHTFIATGREEN6000Bob JonesBob Smith23 Mar 1981 SC04 BFESMARTBLUE13000Bob Smith23 Mar 1981 F611 AAAFORDRED12000Jim SmithBob Jones3 Dec 1986 J111 BBBSKODABLUE11000Jim SmithBob Jones3 Dec 1986 A155 BDEMERCEDESBLUE22000Bob SmithBob Jones3 Dec 1986 K555 GHTFIATGREEN6000Bob Jones 3 Dec 1986 SC04 BFESMARTBLUE13000Bob Jones3 Dec 1986  To make the prior query a proper “join” of the two tables, we add the following WHERE clause row restriction:  WHERE Car.Owner = Driver.Name

Traditional join syntax SELECT * FROM car, driver WHERE owner = name REGNOMAKECOLOURPRICEOWNERNAMEDOB F611 AAAFORDRED12000Jim Smith 11 Jan 1980 J111 BBBSKODABLUE11000Jim Smith 11 Jan 1980 A155 BDEMERCEDESBLUE22000Bob Smith 23 Mar 1981 K555 GHTFIATGREEN6000Bob Jones 3 Dec 1986

An alternative syntax for the join in SQL SELECT * FROM car JOIN driver ON ( owner = name ) REGNOMAKECOLOURPRICEOWNERNAMEDOB F611 AAAFORDRED12000Jim Smith 11 Jan 1980 J111 BBBSKODABLUE11000Jim Smith 11 Jan 1980 A155 BDEMERCEDESBLUE22000Bob Smith 23 Mar 1981 K555 GHTFIATGREEN6000Bob Jones 3 Dec 1986

Outer joins  Now let’s learn about the “outer join”  The 3 variations on the outer join are the…  Left outer join  Right outer join  Full outer join

OUTER JOIN  Consider the last row shown in the large table 4 slides back  This is a car without an owner (due to the “blank”)  Sometimes we want to see the “unmatched rows” that fail the join condition due to NULL (blank) values.  This idea is referred to as performing an “outer join.”  There are “left” and “right” outer joins, depending on which rows you want to keep.  The join operation we have discussed prior to now is known as a standard “inner” join. REGNOMAKECOLOURPRICEOWNERNAMEDOB SC04 BFESMARTBLUE13000Bob Jones3 Dec 1986

 Consider this: SELECT * FROM car JOIN driver on (driver = name) To the LEFT of the JOINTo the RIGHT of the JOIN  If you want all the rows in CAR to always be in the answer (whether matched or unmatched), you need a “ left outer join”  If you want all the rows in DRIVER to always be in the answer (whether matched or unmatched), you need a “ right outer join”  What if you want to keep all the rows from both sides?  You need a “full outer join,” known as simply a FULL JOIN.

SELECT * FROM car LEFT JOIN driver ON ( owner = name ) REGNOMAKECOLOURPRICEOWNERNAMEDOB F611 AAAFORDRED12000Jim Smith 11 Jan 1980 J111 BBBSKODABLUE11000Jim Smith 11 Jan 1980 A155 BDEMERCEDESBLUE22000Bob Smith 23 Mar 1981 K555 GHTFIATGREEN6000Bob Jones 3 Dec 1986 SC04 BFESMARTBLUE13000

SELECT * FROM car RIGHT JOIN driver ON ( owner = name ) REGNOMAKECOLOURPRICEOWNERNAMEDOB F611 AAAFORDRED12000Jim Smith 11 Jan 1980 J111 BBBSKODABLUE11000Jim Smith 11 Jan 1980 A155 BDEMERCEDESBLUE22000Bob Smith 23 Mar 1981 K555 GHTFIATGREEN6000Bob Jones 3 Dec 1986 David Davis1 Oct 1975 NAMEDOB Jim Smith11 Jan 1980 Bob Smith23 Mar 1981 Bob Jones3 Dec 1986 David Davis1 Oct 1975

Example: Full outer join SELECT * FROM car FULL JOIN driver ON ( owner = name ) REGNOMAKECOLOURPRICEOWNERNAMEDOB F611 AAAFORDRED12000Jim Smith 11 Jan 1980 J111 BBBSKODABLUE11000Jim Smith 11 Jan 1980 A155 BDEMERCEDESBLUE22000Bob Smith 23 Mar 1981 K555 GHTFIATGREEN6000Bob Jones 3 Dec 1986 SC04 BFESMARTBLUE13000 David Davis1 Oct 1975