CS411 Database Systems Kazuhiro Minami 06: SQL. SQL = Structured Query Language Standard language for querying and manipulating data Has similar capabilities.

Slides:



Advertisements
Similar presentations
1 Introduction to SQL Select-From-Where Statements Subqueries Grouping and Aggregation.
Advertisements

Union, Intersection, Difference (subquery) UNION (subquery) produces the union of the two relations. Similarly for INTERSECT, EXCEPT = intersection and.
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.
SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: SQL92, SQL2, SQL3. Vendors support.
1 Relational Algebra* and Tuple Calculus * The slides in this lecture are adapted from slides used in Standford's CS145 course.
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.
1 Relational Algebra. Motivation Write a Java program Translate it into a program in assembly language Execute the assembly language program As a rough.
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.
SQL CSET 3300.
Relational Algebra (end) SQL April 19 th, Complex Queries Product ( pid, name, price, category, maker-cid) Purchase (buyer-ssn, seller-ssn, store,
CS411 Database Systems Kazuhiro Minami 06: SQL. Join Expressions.
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.
From Relational Algebra to the Structured Query Language Rose-Hulman Institute of Technology Curt Clifton.
IS698: Database Management Min Song IS NJIT. Overview  Query processing  Query Optmization  SQL.
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 2008 Instructor: Jianer Chen Office: HRBB 309B Phone: Notes #3.
CPSC-608 Database Systems Fall 2011 Instructor: Jianer Chen Office: HRBB 315C Phone: Notes #2.
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.
Cursors in Pl/SQL Database 1. Practice. Sample Database The schema of the sample database is the following: Drinkers (name, occupation, birthday, salary)
Integrity Constraints An important functionality of a DBMS is to enable the specification of integrity constraints and to enforce them. Knowledge of integrity.
Exercises Product ( pname, price, category, maker) Purchase (buyer, seller, store, product) Company (cname, stock price, country) Person( per-name, phone.
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.
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.
Constraints on Relations Foreign Keys Local and Global Constraints Triggers Following lecture slides are modified from Jeff Ullman’s slides
Onsdag The concepts in a relation data model SQL DDL DML.
Computational Biology Dr. Jens Allmer Lecture Slides Week 6.
Databases 1 Second lecture.
1 CSCE Database Systems Anxiao (Andrew) Jiang The Database Language SQL.
CMPT 258 Database Systems The Relationship Model (Chapter 3)
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.
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.
603 Database Systems Senior Lecturer: Laurie Webster II, M.S.S.E.,M.S.E.E., M.S.BME, Ph.D., P.E. Lecture 18 A First Course in Database Systems.
Select-From-Where Statements Multirelation Queries Subqueries
CPSC-310 Database Systems
Summary of Relational Algebra
Schedule Today: Jan. 28 (Mon) Jan. 30 (Wed) Next Week Assignments !!
CPSC-310 Database Systems
Computational Biology
Outerjoins, Grouping/Aggregation Insert/Delete/Update
CPSC-310 Database Systems
Relational Algebra at a Glance
Schedule Today: Next After that Subqueries, Grouping and Aggregation.
Introduction to Database Systems, CS420
SQL Introduction Standard language for querying and manipulating data
CPSC-608 Database Systems
06a: SQL-1 The Basics– Select-From-Where
CS 440 Database Management Systems
CPSC-608 Database Systems
Database Models Relational Model
IST 210: Organization of Data
Relational Databases The Relational Model.
SQL Introduction Standard language for querying and manipulating data
Where are we? Until now: Modeling databases (ODL, E/R): all about the schema Now: Manipulating the data: queries, updates, SQL Then: looking inside -
CS4433 Database Systems SQL - Basics.
CPSC-608 Database Systems
CPSC-608 Database Systems
More SQL Extended Relational Algebra Outerjoins, Grouping/Aggregation
Syllabus Introduction Website Management Systems
CPSC-608 Database Systems
CMSC-461 Database Management Systems
Instructor: Zhe He Department of Computer Science
Select-From-Where Statements Multirelation Queries Subqueries
Presentation transcript:

CS411 Database Systems Kazuhiro Minami 06: SQL

SQL = Structured Query Language Standard language for querying and manipulating data Has similar capabilities for queries to those in relational algebra Support statements for modifying a database (e.g., inserting and deleting tuples) and for declaring a database schema Many standards: SQL92, SQL2, SQL3, SQL99 We cover features that conform with SQL99

What is special about SQL? You describe what you want, and the job of the DBMS is to figure out how to compute what you want efficiently. (at least in theory)

The basic form of a SQL query is select-from-where SELECT desired attributes FROM one or more tables WHERE condition on the rows of the tables Project out everything not in the final answer Every table you want to join, together All the join and selection conditions

Single-Relation Queries

What beers are made by Anheuser-Busch? Beers(name, manf) Name Bud Bud Lite Michelob SELECT name FROM Beers WHERE manf = Anheuser-Busch; In relational algebra : [manf = Anheuser-Busch] Beers NameManf BudAnheuser-Busch Bud LiteAnheuser-Busch MichelobAnheuser-Busch Super DryAsahi

These simple queries can be translated to relational algebra 1.Begin with the relation in the FROM clause. 2.Apply the selection indicated by the WHERE clause. 3.Apply the projection indicated by the SELECT clause. SELECT A1, …, An FROM R WHERE condition R[condition][A1, …, An] π [ A1, …, An ] [ condition ] R

Here is a way to think about how the query might be implemented 1.Imagine a tuple variable ranging over each tuple of the relation mentioned in FROM. 2.Check if the current tuple satisfies the WHERE clause. 3.If so, output the attributes/expressions of the SELECT clause using the components of this tuple. ABC AB

Put * in the SELECT clause if you dont want to project out any attributes Beers(name, manf) NameManf BudAnheuser-Busch Bud LiteAnheuser-Busch MichelobAnheuser-Busch SELECT * FROM Beers WHERE manf = Anheuser-Busch;

Find all US companies whose stock is > $500 Company(sticker, name, country, stockPrice) SELECT * FROM Company WHERE country=USA AND stockPrice > 500 StickerNameCountryStockPrice GOOGGoogleUSA550 GOOGAppleUSA485

You can rename the attributes in the result, using as Beers(name, manf) SELECT name AS beer, manf FROM Beers WHERE manf = Anheuser-Busch; BeerManf BudAnheuser-Busch Bud LiteAnheuser-Busch MichelobAnheuser-Busch

You can use math in the SELECT clause Sells(bar, beer, price) SELECT bar, bEeR, price*120 AS priceInYen FROM Sells; BarBeerPriceInYen JoesBud300 SuesAsahi360 ……… Case-insensitive, except inside quoted strings

You can create a new column and give it a constant value, in the SELECT clause DrinkerWhoLikesBud SallyLikes Bud FredLikes Bud SELECT drinker, Likes Bud AS WhoLikesBud FROM Likes WHERE beer = Bud; Likes(Drinker, beer) DrinkerBeer SallyBud FredBud

Find the price Joes Bar charges for Bud. Sells(bar, beer, price) SELECT price FROM Sells WHERE bar = Joes Bar AND beer = Bud; Two single quotes inside a string = one apostrophe

What you can use in the WHERE clause conditions: constants of any supported type attribute names of the relation(s) used in the FROM arithmetic operations: stockprice*2 operations on strings (e.g., || for concatenation) comparison operators: =, <>,, = lexicographic order on strings (<) string pattern matching: s LIKE p special functions for comparing dates and times and combinations of the above using AND, OR, NOT, and parentheses

attr LIKE pattern does pattern matching on strings pattern is a quoted string that may contain two special symbols: phone LIKE %555-_ _ _ _ address LIKE %Mountain% SymbolWhat It Matches % matches any sequence of characters _ matches any single character

Find the drinkers with phone prefix 555 Drinkers(name, addr, phone) SELECT name FROM Drinkers WHERE phone LIKE %555-____;

Find all US companies whose address contains Mountain Company(sticker, name, address, country, stockPrice) SELECT * FROM Company WHERE country=USA AND address LIKE %Mountain%;

What if an attribute value is unknown, or the attribute is inapplicable (e.g., my daughters spouse) ? SELECT bar FROM Sells WHERE price = 2.00; Bar Jillians Why??? BarBeerPrice JilliansBud2.00 White Horse InnAsahiNULL

Conditions involving NULL evaluate to unknown, rather than true or false Example condition Evaluates to Smith = Smith true 2 > 6 false Smith = NULL unknown 2 < NULL unknown true AND unknownunknown true OR unknowntrue false AND unknownfalse false OR unknownunknown unknown OR unknownunknown A tuple only goes in the answer if its truth value for the WHERE clause is true.

The law of the excluded middle doesnt hold in this 3- valued logic SELECT bar FROM Sells WHERE price = 2.00; unknown BarBeerPrice White Horse InnAsahiNULL unknown

SQL code writers spend a lot of space dealing with NULL values Can test for NULL explicitly: x IS NULL x IS NOT NULL SELECT * FROM Person WHERE age = 25 OR age IS NULL The answer includes all Persons!

Exercise 1: online bookstore Book(isbn, title, publisher, price) Author(assn, aname, isbn) Customer(cid, cname, state, city, zipcode) Buy(tid, cid, isbn, year, month, day) Q1: Make a list of the ISBNs and titles of books whose price is greater than $1000? SELECT isbn, title FROM Book WHERE price > 1000

Multi-Relation Queries

If you need to join several relations, you can list them all in the FROM clause SELECT bar FROM Sells, Likes WHERE drinker = Alice AND Likes.beer = Sells.beer; List the bars that serve a beer that Alice likes. Likes(drinker, beer) Sells(bar, beer, price) This is how we disambiguate attribute names. π [bar](Sells [drinker =Alice] Likes)

Find the beers liked by at least one person who frequents Murphys Pub SELECT beer AS beersWorthKeeping FROM Likes, Frequents WHERE bar = Murphys Pub AND Frequents.drinker = Likes.drinker; BeersWorthKeeping Samuel Adams Pale Ale … Likes(drinker, beer) Frequents(drinker, bar) π [beer] (Likes [bar = Murphys Pub] Frequents)

Find names of people living in Champaign who bought snow shovels, and the names of the stores where they bought them Purchase (buyer, seller, store, product) Person(pname, phoneNumber, city ) SELECT pname, store FROM Person, Purchase WHERE pname = buyer AND city = Champaign AND product = snow shovel; π [pname, store]( [city = Champaign] Person Pname = buyer [product=snow shovel] Purchase)

You can also join three or more relations, just like in relational algebra Product (name, price, category, maker) Purchase (buyer, seller, store, product) Person (name, phoneNumber, city) Find names and phone numbers of people buying telephony products. SELECT Person.name, Person.phoneNumber FROM Person, Purchase, Product WHERE Person.name=Purchase.buyer AND Purchase.product=Product.name AND Product.category=telephony SELECT Person.name, Person.phoneNumber FROM Person, Purchase, Product WHERE Person.name=Purchase.buyer AND Purchase.product=Product.name AND Product.category=telephony

What should be in the answer when the query involves a join? 1.Create the cartesian product of all the relations in the FROM clause. 2.Then remove all the tuples that dont satisfy the selection condition in the WHERE clause. 3.Project the remaining tuples onto the list of attributes/expressions in the SELECT clause.

An algorithm for computing the answer 1.Imagine one tuple variable for each relation mentioned in FROM. These tuple- variables visit each combination of tuples, one from each relation. 2.Whenever the tuple- variables are pointing to tuples that satisfy the WHERE clause, send these tuples to the SELECT clause. ABC ABE DE

Exercise 2: online bookstore Book(isbn, title, publisher, price) Author(assn, aname, isbn) Customer(cid, cname, state, city, zipcode) Buy(tid, cid, isbn, year, month, day) Q2: Make a list of the CIDs and customer names who bought books written by Barack Obama? SELECT Customer.cid, Customer.cname FROM Author, Buy, Customer WHERE Customer.cid = Buy.cid AND Buy.isbn = Author.ibn AND Author.name = `Barack Obama ;