SQL CSET 3300.

Slides:



Advertisements
Similar presentations
Union, Intersection, Difference (subquery) UNION (subquery) produces the union of the two relations. Similarly for INTERSECT, EXCEPT = intersection and.
Advertisements

SQL Group Members: Shijun Shen Xia Tang Sixin Qiang.
1 Introduction to SQL Select-From-Where Statements Multirelation Queries Subqueries.
SQL Queries Principal form: SELECT desired attributes FROM tuple variables –– range over relations WHERE condition about tuple variables; Running example.
Winter 2002Arthur Keller – CS 1806–1 Schedule Today: Jan. 22 (T) u SQL Queries. u Read Sections Assignment 2 due. Jan. 24 (TH) u Subqueries, Grouping.
CS411 Database Systems Kazuhiro Minami 06: SQL. Join Expressions.
1 Database Systems Relations as Bags Grouping and Aggregation Database Modification.
1 Introduction to SQL Multirelation Queries Subqueries Slides are reused by the approval of Jeffrey Ullman’s.
Subqueries Example Find the name of the producer of ‘Star Wars’.
IS698: Database Management Min Song IS NJIT. Overview  Query processing  Query Optmization  SQL.
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.
Fall 2001Arthur Keller – CS 1806–1 Schedule Today (TH) Bags and SQL Queries. u Read Sections Project Part 2 due. Oct. 16 (T) Duplicates, Aggregation,
CPSC-608 Database Systems Fall 2011 Instructor: Jianer Chen Office: HRBB 315C Phone: Notes #3.
SQL SQL is a very-high-level language, in which the programmer is able to avoid specifying a lot of data-manipulation details that would be necessary in.
Joins Natural join is obtained by: R NATURAL JOIN S; Example SELECT * FROM MovieStar NATURAL JOIN MovieExec; Theta join is obtained by: R JOIN S ON Example.
CPSC-608 Database Systems Fall 2008 Instructor: Jianer Chen Office: HRBB 309B Phone: Notes #3.
Winter 2002Arthur Keller – CS 1807–1 Schedule Today: Jan. 24 (TH) u Subqueries, Grouping and Aggregation. u Read Sections Project Part 2 due.
1 More SQL Extended Relational Algebra Outerjoins, Grouping/Aggregation Insert/Delete/Update.
CPSC-608 Database Systems Fall 2011 Instructor: Jianer Chen Office: HRBB 315C Phone: Notes #2.
Chapter 6 Notes. 6.1 Simple Queries in SQL SQL is not usually used as a stand-alone language In practice there are hosting programs in a high-level language.
SQL 2014, Fall Pusan National University Ki-Joune Li These slides are made from the materials that Prof. Jeffrey D. Ullman distributes via his course web.
SCUHolliday6–1 Schedule Today: u SQL Queries. u Read Sections Next time u Subqueries, Grouping and Aggregation. u Read Sections And then.
Databases : SQL-Introduction 2007, Fall Pusan National University Ki-Joune Li These slides are made from the materials that Prof. Jeffrey D. Ullman distributes.
1 IT 244 Database Management System Lecture 11 SQL Select-From-Where Statements Meaning of queries Subqueries Ref : -A First Course in Database System.
Constraints on Relations Foreign Keys Local and Global Constraints Triggers Following lecture slides are modified from Jeff Ullman’s slides
1 Introduction to SQL. 2 Why SQL? SQL is a very-high-level language, in which the programmer is able to avoid specifying a lot of data-manipulation details.
Onsdag The concepts in a relation data model SQL DDL DML.
SQL 2015, Fall Pusan National University Ki-Joune Li These slides are made from the materials that Prof. Jeffrey D. Ullman distributes via his course web.
Computational Biology Dr. Jens Allmer Lecture Slides Week 6.
1 Introduction to SQL Select-From-Where Statements Multirelation Queries Subqueries Slides are reused by the approval of Jeffrey Ullman’s.
Databases 1 Second lecture.
1 CSCE Database Systems Anxiao (Andrew) Jiang The Database Language SQL.
1 Introduction to SQL Database Systems. 2 Why SQL? SQL is a very-high-level language, in which the programmer is able to avoid specifying a lot of data-manipulation.
1 Introduction to SQL. 2 Why SQL? SQL is a very-high-level language, in which the programmer is able to avoid specifying a lot of data-manipulation details.
Introduction to SQL Introduction Select-From-Where Statements Queries over Several Relations Subqueries.
Himanshu GuptaCSE 532-SQL-1 SQL. Himanshu GuptaCSE 532-SQL-2 Why SQL? SQL is a very-high-level language, in which the programmer is able to avoid specifying.
SCUHolliday - coen 1787–1 Schedule Today: u Subqueries, Grouping and Aggregation. u Read Sections Next u Modifications, Schemas, Views. u Read.
More SQL (and Relational Algebra). More SQL Extended Relational Algebra Outerjoins, Grouping/Aggregation Insert/Delete/Update.
Databases : SQL Multi-Relations 2007, Fall Pusan National University Ki-Joune Li These slides are made from the materials that Prof. Jeffrey D. Ullman.
1 Introduction to SQL Select-From-Where Statements Subqueries Grouping and Aggregation.
1 Introduction to Database Systems, CS420 SQL JOIN, Aggregate, Grouping, HAVING and DML Clauses.
1 Database Design: DBS CB, 2 nd Edition SQL: Select-From-Where Statements & Multi-relation Queries & Subqueries Ch. 6.
Select-From-Where Statements Multirelation Queries Subqueries
Schedule Today: Jan. 28 (Mon) Jan. 30 (Wed) Next Week Assignments !!
Slides are reused by the approval of Jeffrey Ullman’s
CPSC-310 Database Systems
Computational Biology
Outerjoins, Grouping/Aggregation Insert/Delete/Update
Databases : More about SQL
CPSC-310 Database Systems
Schedule Today: Next After that Subqueries, Grouping and Aggregation.
Introduction to Database Systems, CS420
CPSC-608 Database Systems
06a: SQL-1 The Basics– Select-From-Where
CS 440 Database Management Systems
CPSC-608 Database Systems
Database Design and Programming
CPSC-310 Database Systems
IST 210: Organization of Data
CPSC-310 Database Systems
IT 244 Database Management System
2018, Fall Pusan National University Ki-Joune Li
CPSC-608 Database Systems
CPSC-608 Database Systems
More SQL Extended Relational Algebra Outerjoins, Grouping/Aggregation
CPSC-608 Database Systems
CPSC-608 Database Systems
Instructor: Zhe He Department of Computer Science
Select-From-Where Statements Multirelation Queries Subqueries
Presentation transcript:

SQL CSET 3300

Select-From-Where Statements Meaning of queries Subqueries Introduction to SQL Select-From-Where Statements Meaning of queries Subqueries 2

Why SQL? SQL is a very-high-level language, in which the programmer is able to avoid specifying a lot of data-manipulation details that would be necessary in languages like C++. What makes SQL viable is that its queries are “optimized” quite well, yielding efficient query executions. 3

Select-From-Where Statements The principal form of a query is: SELECT desired attributes FROM one or more tables WHERE condition about tuples of the tables 4

Our DB Schema DB schema for SQL queries Beers(name, manf) Underline indicates key attributes. Beers(name, manf) Bars(name, addr, license) Drinkers(name, addr, phone) Likes(drinker, beer) Sells(bar, beer, price) Frequents(drinker, bar) 5

SQL “Select” Example Using Beers(name, manf), what beers are made by Anheuser-Busch? SELECT name FROM Beers WHERE manf = ‘Anheuser-Busch’ name Bud Lite Michelob Bud The answer is a relation with a single attribute- name, and tuples with the name of each beer by Anheuser-Busch, such as Bud. 6

“*” In SELECT Clauses When there is one relation in the FROM clause, * in the SELECT clause stands for “all attributes of this relation.” Example using Beers(name, manf): SELECT * FROM Beers WHERE manf = ‘Anheuser-Busch’ name manf Bud Anheuser-Busch Bud Lite Michelob 7

Renaming Attributes If you want the result to have different attribute names, use “AS <new name>” to rename an attribute. Example based on Beers(name, manf): SELECT name AS beer, manf FROM Beers WHERE manf = ‘Anheuser-Busch’ beer manf Bud Anheuser-Busch Bud Lite Michelob 8

Expressions in SELECT Clauses Any expression that makes sense can appear as an element of a SELECT clause. Example: from Sells(bar, beer, price): SELECT bar, beer, price * 120 AS priceInYen FROM Sells; bar beer priceInYen Joe’s Bud 300 Sue’s Bud Lite 350 … 9

Another Example: Constant Expressions From Likes(drinker, beer): SELECT drinker, ‘likes Bud’ AS whoLikesBud FROM Likes WHERE beer = ‘Bud’; Drinker whoLikesBud Sally Likes Bud Fred …. 10

Complex Conditions in WHERE Clause From Sells(bar, beer, price): find the price Joe’s Bar charges for Bud: SELECT price FROM Sells WHERE bar = ‘Joe’’s Bar’ AND beer = ‘Bud’; 11

Important Points Two single quotes inside a string represent the single-quote (apostrophe). Conditions in the WHERE clause can use AND, OR, NOT, and parentheses in the usual way boolean conditions are built. SQL is case-insensitive. In general, upper and lower case characters are the same, except inside quoted strings. 12

Patterns in SQL Where Clauses WHERE clauses can have conditions in which a string is compared with a pattern, to see if it matches. General form: <Attribute> LIKE <pattern> or <Attribute> NOT LIKE <pattern> Pattern is a quoted string with % = “any string” _ = “any character.” 13

Example From Drinkers(name, addr, phone): find the drinkers with exchange 555: SELECT name FROM Drinkers WHERE phone LIKE ‘%555-_ _ _ _’ 14

Relations with NULL Values Tuples in SQL relations can have NULL as a value for one or more components. Meaning depends on context. Two common cases: Missing value : e.g., we know Joe’s Bar has some address, but we don’t know what it is. Inapplicable : e.g., the value of attribute spouse for an unmarried person. The logic of conditions in SQL is really 3-valued logic: TRUE, FALSE, UNKNOWN. When any value is compared with NULL, the truth value is UNKNOWN. But a query only produces a tuple in the answer if its truth value for the WHERE clause is TRUE (not FALSE or UNKNOWN) 15

Example for Relations with NULL From the following Sells relation: SELECT bar FROM Sells WHERE price < 2.00 OR price >= 2.00; => We get only “Joe’s” bar bar beer Price Joe’s Bud 3.00 Sue’s Bud Lite NULL … 16

Ordering the Output Tuples produced by a query can be presented in sorted order. To get output in sorted order ORDER BY <list of attributes> Default order is ascending For descending order append the keyword “DESC” to an attribute 17

Example Suppose we have a movies relation SELECT * Movie (title, year, length, studioName, producerNo) SELECT * FROM Movie WHERE studioName=“Disney” AND year= “2008” ORDER BY length, title 18

Example Using Beers(name, manf) SELECT b1.name, b2.name Find all pairs of beers by the same manufacturer. Do not produce pairs like (Bud, Bud). Produce pairs in alphabetic order, e.g. (Bud, Miller), not (Miller, Bud). SELECT b1.name, b2.name FROM Beers b1, Beers b2 WHERE b1.manf = b2.manf AND b1.name < b2.name 19

Subqueries A parenthesized SELECT-FROM-WHERE statement (subquery) can be used as a value in a number of places, including FROM and WHERE clauses. Example: in place of a relation in the FROM clause, we can place another query, and then query its result. Better use a tuple-variable to name tuples of the result. If a subquery is guaranteed to produce one tuple, then the subquery can be used as a value. 20

Example Using Sells(bar, beer, price) Two queries would surely work: Find the bars that serve Miller for the same price Joe’s bar charges for Bud. Two queries would surely work: Find the price Joe’s bar charges for Bud. Find the bars that serve Miller at that price. 21

Query & Subquery Solution SELECT bar FROM Sells WHERE beer = ‘Miller’ AND price = (SELECT price WHERE bar = ‘Joe’’s Bar’ AND beer = ‘Bud’) The price at which Joe sells Bud 22

The IN Operator <tuple> IN <relation> is true if and only if the tuple is a member of the relation. <tuple> NOT IN <relation> means the opposite. IN-expressions can appear in WHERE clauses. The <relation> is often a subquery. 23

Example Using Beers(beer, manf) and Likes(drinker, beer) SELECT * Find the beer and manufacturer of each beer that Fred likes. SELECT * FROM Beers WHERE beer IN (SELECT beer FROM Likes WHERE drinker = ‘Fred’) The set of beers Fred likes 24

The Exists Operator EXISTS( <relation> ) is true if and only if the <relation> is not empty. Being a boolean-valued operator, EXISTS can appear in WHERE clauses. Can use NOT EXISTS also. 25

Example Query with EXISTS Using Beers(beer, manf) and Likes(drinker, beer) Find the beer and manufacturer of each beer that Fred likes. SELECT * FROM Beers B WHERE EXISTS (SELECT * FROM Likes WHERE drinker = ‘Fred’ AND beer = B.beer) 26

The Operator ANY x = ANY( <relation> ) is a boolean condition meaning that x equals at least one tuple in the relation. Similarly, = can be replaced by any of the comparison operators. Example: x >= ANY( <relation> ) means x is not smaller than all tuples in the relation. Note tuples must have one component only. 27

The Operator ALL Similarly, x <> ALL( <relation> ) is true if and only if for every tuple t in the relation, x is not equal to t. That is, x is not a member of the relation. The <> can be replaced by any comparison operator. Example: x >= ALL( <relation> ) means there is no tuple larger than x in the relation. 28

Union, Intersection, and Difference Union, intersection, and difference of relations are expressed by the following forms, each involving subqueries: ( subquery ) UNION ( subquery ) ( subquery ) INTERSECT ( subquery ) ( subquery ) EXCEPT ( subquery ) 29

Example Using Likes(drinker, beer) Sells(bar, beer, price) Visits(drinker, bar) Find the drinkers and beers such that: The drinker likes the beer, and The drinker visits at least one bar that sells the beer. 30

SQL Query (SELECT drinker, beer FROM Likes) INTERSECT FROM Sells, Visits WHERE Visits.bar = Sells.bar ) The drinker visits a bar that sells the beer. 31

Bag Semantics Although the SELECT-FROM-WHERE statement uses bag semantics, the default for union, intersection, and difference is set semantics. That is, duplicates are eliminated as the operation is applied. 32

Controlling Duplicate Elimination Force the result to be a set by SELECT DISTINCT . . . Force the result to be a bag (i.e., don’t eliminate duplicates) by ALL as in . . . UNION ALL . . . 33

Example: DISTINCT Using Sells(bar, beer, price) SELECT DISTINCT price Find all the different prices charged for beers: SELECT DISTINCT price FROM Sells; Notice that without DISTINCT, each price would be listed as many times as there were bar/beer pairs at that price. 34

Aggregations SUM, AVG, COUNT, MIN, and MAX can be applied to a column in a SELECT clause to produce that aggregation on the column. Also, COUNT(*) counts the number of tuples. 35

Example: Aggregation From Sells(bar, beer, price) SELECT AVG(price) Find the average price of Bud: SELECT AVG(price) FROM Sells WHERE beer = ‘Bud’ 36

Eliminating Duplicates in an Aggregation DISTINCT inside an aggregation causes duplicates to be eliminated before the aggregation. Example: find the number of different prices charged for Bud: SELECT COUNT(DISTINCT price) FROM Sells WHERE beer = ‘Bud’ 37

NULL’s Ignored in Aggregation NULL never contributes to a sum, average, or count, and can never be the minimum or maximum of a column. But if there are no non-NULL values in a column, then the result of the aggregation is NULL. 38

Example: Effect of NULL’s SELECT count(*) FROM Sells WHERE beer = ‘Bud’; SELECT count(price) The number of bars that sell Bud. The number of bars that sell Bud at a known price. 39

Grouping We may follow a SELECT-FROM-WHERE expression by GROUP BY and a list of attributes. The relation that results from the SELECT-FROM-WHERE is grouped according to the values of all those attributes Any aggregation can be applied for each group. 40

Example: Grouping From Sells(bar, beer, price) SELECT beer, AVG(price) Find the average price for each beer: SELECT beer, AVG(price) FROM Sells GROUP BY beer; 41

Example: Grouping From Sells(bar, beer, price) and Frequents(drinker, bar) Find for each drinker the average price of Bud at the bars they frequent: SELECT drinker, AVG(price) FROM Frequents, Sells WHERE beer = ‘Bud’ AND Frequents.bar = Sells.bar GROUP BY drinker; Compute drinker-bar- price of Bud tuples first, then group by drinker. 42

Restriction on SELECT Lists! If any aggregation is used, then each element of the SELECT list must be either: Aggregated, or An attribute on the GROUP BY list. You might think you could find the bar that sells Bud the cheapest by: SELECT bar, MIN(price) FROM Sells WHERE beer = ‘Bud’; But this query is illegal in SQL. Why? Note bar is neither aggregated nor on the GROUP BY list. 43

HAVING Clauses HAVING <condition> may follow a GROUP BY clause. If so, the condition applies to each group, and groups not satisfying the condition are eliminated. 44

Example: HAVING From Sells(bar, beer, price) Find the average price of those beers that are served in at least three bars. SELECT beer, AVG(price) FROM Sells GROUP BY beer HAVING COUNT(bar) >= 3 Beer groups with at least 3 bars 45