Docsity

Understanding SQL Querying: Select-From-Where, Multirelation Queries, and Subqueries, Slides of Database Management Systems (DBMS)

Partial preview of the text

Download Understanding SQL Querying: Select-From-Where, Multirelation Queries, and Subqueries and more Slides Database Management Systems (DBMS) in PDF only on Docsity!

Introduction to SQL

Select-From-Where Statements

Multirelation Queries Subqueries

Why SQL?

  • SQL is a very-high-level language.
    • Say “what to do” rather than “how to do it.”
    • Avoid a lot of data-manipulation details needed in procedural languages like C++ or Java.
  • Database management system figures out “best” way to execute query. - Called “query optimization.”

Our Running Example

  • All our SQL queries will be based on the following database schema. - 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)

Example

  • Using Beers(name, manf), what beers are made by Anheuser-Busch? SELECT name FROM Beers WHERE manf = ’Anheuser-Busch’;

Meaning of Single-Relation Query

  • Begin with the relation in the FROM clause.
  • Apply the selection indicated by the WHERE clause.
  • Apply the extended projection indicated by the SELECT clause.

Operational Semantics

8

Check if Anheuser-Busch

name manf

Bud Anheuser-Busch Include t.name in the result, if so

Tuple-variable t loops over all tuples

* 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’;

Result of Query:

name manf Bud Anheuser-Busch Bud Lite Anheuser-Busch Michelob Anheuser-Busch

......

11

Now, the result has each of the attributes of Beers.

Result of Query:

beer manf

Bud Anheuser-Busch

Bud Lite Anheuser-Busch

Michelob Anheuser-Busch

......

Expressions in SELECT Clauses

  • Any expression that makes sense can appear as an element of a SELECT clause.
  • Example: Using Sells(bar, beer, price):

SELECT bar, beer, price*114 AS priceInYen FROM Sells;

Example: Constants as Expressions

  • Using Likes(drinker, beer):

SELECT drinker, ’likes Bud’ AS whoLikesBud FROM Likes WHERE beer = ’Bud’;

Result of Query

drinker whoLikesBud

Sally likes Bud

Fred likes Bud

… …

Information Integration --- (2)

  • For instance, at Joe’s Bar we can issue the query:

SELECT ’Joe’’s Bar’, beer, price

FROM Menu;

Complex Conditions in WHERE

Clause

  • Boolean operators AND, OR, NOT.
  • Comparisons =, <>, <, >, <=, >=.
    • And many other operators that produce boolean- valued results.