1 / 34

Intro. to SQL

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

kanan
Télécharger la présentation

Intro. to SQL

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Intro. to SQL DSC340 Mike Pangburn

  2. 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

  3. 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

  4. A sample database table Attribute names Table name Product Tuples or rows

  5. DB Terminology overview

  6. 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

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

  8. 1-table query with row filtering Product SELECT *FROM ProductWHERE category=‘Gadgets’ “row restriction”

  9. A query projecting specific columns Product “row restriction”with certain columns “projected” SELECTPName, Price, ManufacturerFROM ProductWHERE Price > 100

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

  11. The LIKE operator • sLIKEp: 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 ProductsWHEREPNameLIKE ‘%gizmo%’

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

  13. Ordering the Results SELECTpname, 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.

  14. Ordering the Results SELECT Category FROM Product ORDER BY PName ?

  15. “Joining tables” in SQL Product • Connect two or more tables: Company What is the connection? Do you think the DBMS sees that?

  16. Joinbetween Productand Company 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, PriceFROM Product, CompanyWHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200

  17. Joins using SQL Product Company SELECTPName, PriceFROM Product, CompanyWHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200

  18. 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 CountryFROM Product, CompanyWHERE Manufacturer=CNameAND Category=‘Gadgets’

  19. Joins in SQL Product Company SELECT CountryFROM Product, CompanyWHERE Manufacturer=CName AND Category=‘Gadgets’ What will the two output lines be?Do we recall how to avoid showing identical output rows?

  20. 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. SELECTDISTINCT persname, storeFROM Person, Purchase, ProductWHERE persname=buyer AND product = pname AND city=‘Seattle’ AND category=‘Gadgets’

  21. Disambiguating Attributes • Sometimes two relations have same attributePerson(pname, address, worksfor)Company(cname, address) Whichaddress ? SELECTDISTINCTpname, addressFROM Person, CompanyWHERE worksfor = cname SELECTDISTINCT Person.pname, Company.addressFROM Person, CompanyWHERE Person.worksfor = Company.cname

  22. Renaming Columns Product SELECTPnameAS prodName, Price AS askPriceFROM ProductWHERE Price > 100 Query withrenaming

  23. “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 http://db.grussell.org

  24. Two tables for our example SELECT * from driver; SELECT * from car;

  25. What if you forget the “join condition?” • 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.

  26. Adding the Join condition • 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

  27. Traditional join syntax SELECT * FROM car, driver WHERE owner = name

  28. An alternative syntax for the join in SQL SELECT * FROM car JOIN driver ON ( owner = name )

  29. 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

  30. 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.

  31. 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 “leftouter join” • If you want all the rows in DRIVER to always be in the answer (whether matched or unmatched), you need a “rightouter 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.

  32. SELECT * FROM car LEFT JOIN driver ON ( owner = name )

  33. Row added for this example SELECT * FROM car RIGHT JOIN driver ON ( owner = name )

  34. Example: Full outer join SELECT * FROM car FULL JOIN driver ON ( owner = name )

More Related