3-Lect-Intro SQL -updated

Содержание

Слайд 2

Main Textbook

Database Systems: The Complete Book
Hector Garcia-Molina
Jeffrey D. Ullman
Jennifer Widom

Main Textbook Database Systems: The Complete Book Hector Garcia-Molina Jeffrey D. Ullman Jennifer Widom

Слайд 3

Alternative Textbook

Database Management Systems
Raghu Ramakrishnan
Johannes Gehrke

Alternative Textbook Database Management Systems Raghu Ramakrishnan Johannes Gehrke

Слайд 4

Goals of Course

To obtain a firm background in database systems, e.g.,
how to

Goals of Course To obtain a firm background in database systems, e.g.,
talk to database systems in a standard language
how to improve the efficiency of database systems
the theories behind database design and some algorithms behind database implementation
Mostly “basic stuff” about databases

Слайд 5

What will NOT be taught

Advanced database technologies
Geographical information systems
Data mining

(This is an

What will NOT be taught Advanced database technologies Geographical information systems Data
introductory course only)
Specific instructions on how to install and use a specific database system on a specific platform
Try the user manual or Google

Слайд 6

Teaching Style

There will be a lot of in-lecture exercises
Questions will be welcomed
Lecture

Teaching Style There will be a lot of in-lecture exercises Questions will
notes will be released on the Drive (at least several days before lectures)

Слайд 7

Course Overview

What is a database?
A large collection of data organized especially for

Course Overview What is a database? A large collection of data organized
rapid search and retrieval (as by a computer)
What is a database system? (more formally, a database management system, i.e., DBMS)
A management system that helps us retrieve information from databases

Слайд 8

Database and DBMS

Database

Database Management System

User

What is the average annual income of a Kazakhstan tax

Database and DBMS Database Database Management System User What is the average
payer?

KZT *****

Слайд 9

Tables, Relations, Relational Model

Database

Database Management System

User

Income_Table

Tables, Relations, Relational Model Database Database Management System User Income_Table

Слайд 10

Tables, Relations, Relational Model

Database

Database Management System

User

Income_Table

What is the average annual income of a Kazakhstan

Tables, Relations, Relational Model Database Database Management System User Income_Table What is
tax payer?

???

Слайд 11

Structured Query Language (SQL)

Database

Database Management System

User

Income_Table

SELECT avg(Annual_Income) FROM Income_Table

Structured Query Language (SQL) Database Database Management System User Income_Table SELECT avg(Annual_Income) FROM Income_Table

Слайд 12

Structured Query Language (SQL)

Database

Database Management System

User

Income_Table

SELECT avg(Annual_Income) FROM Income_Table

More details about SQL will be covered

Structured Query Language (SQL) Database Database Management System User Income_Table SELECT avg(Annual_Income)
later today

Слайд 13

Database Schema Design

Database

Database Management System

User

You should store XXX and YYY in two different tables,

Database Schema Design Database Database Management System User You should store XXX
and blah blah blah..

Yes sir!

Слайд 14

Database Schema Design

Assume that we want to capture parent-child relationships

Database Schema Design Assume that we want to capture parent-child relationships

Слайд 15

Database Schema Design

Is one column enough?

Database Schema Design Is one column enough?

Слайд 16

Database Schema Design

Are two columns enough?
Assume that two columns are enough
Does everyone

Database Schema Design Are two columns enough? Assume that two columns are
have two children?

Schema designs based on the Entity-Relationship model

Слайд 17

Course Content

SQL
Constraints and Triggers
Conceptual Design
Indices
Relation Algebra
Query Processing/Optimization
Concurrency Control
Recovery
Current trend (e.g., NOSQL)

Database Design

Database

Course Content SQL Constraints and Triggers Conceptual Design Indices Relation Algebra Query
Implementation

Слайд 18

What do you want from a DBMS?

Why do we need it?

Keep

What do you want from a DBMS? Why do we need it?
data around (persistent)
Answer queries (questions) about data
Update data
Requirements from high-end applications
Massive amounts of data (terabytes ~ petabytes)
High throughput (thousands ~ millions transactions/min)

Слайд 19

The Relational Revolution

The Relational Revolution (1970’s)

IBM and Univ of Berkeley
A simple data

The Relational Revolution The Relational Revolution (1970’s) IBM and Univ of Berkeley
model: Data is stored in relations (tables)
A declarative query language: SQL
Programmer specifies what answers a query should return, but not how the query is executed
DBMS picks the best execution strategy
Hide the physical organization of the database from applications
Provided only logical view of the data

Relational model is the dominating technology today
Graphs/Streams/Arrays are hot wanna-be!

Слайд 20

“Relational databases are the foundation of western civilization.”

Bruce Lindsay
IBM Fellow
IBM Almaden Research

“Relational databases are the foundation of western civilization.” Bruce Lindsay IBM Fellow IBM Almaden Research Center
Center

Слайд 21

Structured Query Language (SQL)

Structured Query Language (SQL)

Слайд 22

Structured Query Language (SQL)

A declarative (computer) language for managing data in a

Structured Query Language (SQL) A declarative (computer) language for managing data in
relational database management system
Two parts
Data Definition Language (DDL)
Create/Alter/Delete tables
Will be discussed in the next week
Data Manipulation Language (DML)
Query one or more tables
Insert/Delete/Modify tuples in tables
Will be discussed in the following

Слайд 23

Tables in SQL

Product

Table name

Attribute name

Tuple (i.e. row, record)

Key

Tables in SQL Product Table name Attribute name Tuple (i.e. row, record) Key

Слайд 24

Data Types in SQL

Character strings
CHAR(20)
VARCHAR(50)

Numbers
INT
FLOAT

Others
BOOLEAN
DATETIME

Product

Data Types in SQL Character strings CHAR(20) VARCHAR(50) … Numbers INT FLOAT

Слайд 25

Simple SQL Query

Product

SELECT * FROM Product WHERE Category = ‘Phone’

“selection”

Simple SQL Query Product SELECT * FROM Product WHERE Category = ‘Phone’ “selection”

Слайд 26

Simple SQL Query

Product

SELECT * FROM Product WHERE Category <> ‘Phone’

Simple SQL Query Product SELECT * FROM Product WHERE Category ‘Phone’

Слайд 27

Simple SQL Query

Product

SELECT * FROM Product WHERE Category = ‘Phone’ AND Price > 800

Simple SQL Query Product SELECT * FROM Product WHERE Category = ‘Phone’ AND Price > 800

Слайд 28

Simple SQL Query

Product

SELECT * FROM Product WHERE Category = ‘Tablet’ OR Price > 1000

Simple SQL Query Product SELECT * FROM Product WHERE Category = ‘Tablet’ OR Price > 1000

Слайд 29

Simple SQL Query (cont.)

Product

SELECT PName, Price, Manufacturer FROM Product WHERE Price > 800

“selection and projection”

Simple SQL Query (cont.) Product SELECT PName, Price, Manufacturer FROM Product WHERE

Слайд 30

Details

SQL is NOT case sensitive (when it comes to keywords and names)
SELECT

Details SQL is NOT case sensitive (when it comes to keywords and
= Select = select
Product = product
Constants must use single quotes
‘abc’ – OK
“abc” – NOT OK

Слайд 31

Patterns for Strings

Product

SELECT * FROM Product WHERE PName LIKE ‘iPh%’

% stands for “any string”

Patterns for Strings Product SELECT * FROM Product WHERE PName LIKE ‘iPh%’

Слайд 32

Patterns for Strings

Product

SELECT * FROM Product WHERE PName LIKE ‘%Ph%’

% stands for “any string”

Patterns for Strings Product SELECT * FROM Product WHERE PName LIKE ‘%Ph%’

Слайд 33

Patterns for Strings

Product

SELECT * FROM Product WHERE PName LIKE ‘%P%e%’

% stands for “any string”

Patterns for Strings Product SELECT * FROM Product WHERE PName LIKE ‘%P%e%’

Слайд 34

Patterns for Strings

Product

SELECT * FROM Product WHERE PName LIKE ‘_Phone 4’

_ stands for “any

Patterns for Strings Product SELECT * FROM Product WHERE PName LIKE ‘_Phone
character”

Слайд 35

Patterns for Strings

Product

SELECT * FROM Product WHERE PName LIKE ‘_Phone__’

_ stands for “any character”

Patterns for Strings Product SELECT * FROM Product WHERE PName LIKE ‘_Phone__’

Слайд 36

Patterns for Strings

Product

SELECT * FROM Product WHERE PName NOT LIKE ‘_Phone__’

Patterns for Strings Product SELECT * FROM Product WHERE PName NOT LIKE ‘_Phone__’

Слайд 37

Eliminating Duplicates

Product

SELECT Category FROM Product

Eliminating Duplicates Product SELECT Category FROM Product

Слайд 38

Eliminating Duplicates (cont.)

Product

SELECT DISTINCT Category FROM Product

Eliminating Duplicates (cont.) Product SELECT DISTINCT Category FROM Product

Слайд 39

Ordering the Results

SELECT PName, Price FROM Product WHERE Price < 800 ORDER BY PName

Product

Ordering the Results SELECT PName, Price FROM Product WHERE Price Product

Слайд 40

Ordering the Results (cont.)

SELECT PName, Price FROM Product WHERE Price < 800 ORDER BY PName

Ordering the Results (cont.) SELECT PName, Price FROM Product WHERE Price Product
DESC

Product

Слайд 41

Ordering the Results (cont.)

SELECT PName, Category FROM Product WHERE Price < 1000 ORDER BY Category,

Ordering the Results (cont.) SELECT PName, Category FROM Product WHERE Price Product
PName

Product

Слайд 42

Ordering the Results (cont.)

SELECT PName, Category FROM Product WHERE Price < 1000 ORDER BY Category

Ordering the Results (cont.) SELECT PName, Category FROM Product WHERE Price Product
DESC, PName

Product

Слайд 43

Ordering the Results (cont.)

SELECT PName, Category FROM Product WHERE Price < 1000 ORDER BY Category

Ordering the Results (cont.) SELECT PName, Category FROM Product WHERE Price Product
DESC, PName DESC

Product

Слайд 44

Exercise

SELECT DISTINCT Category FROM Product ORDER BY Category

Product

?

Exercise SELECT DISTINCT Category FROM Product ORDER BY Category Product ?

Слайд 45

Exercise

Product

SELECT DISTINCT Category FROM Product ORDER BY Category

Exercise Product SELECT DISTINCT Category FROM Product ORDER BY Category

Слайд 46

Exercise

SELECT DISTINCT Category FROM Product ORDER BY Category WHERE Price < 1000

Product

?

Exercise SELECT DISTINCT Category FROM Product ORDER BY Category WHERE Price Product ?

Слайд 47

Exercise

“WHERE” should always proceed “ORDER BY”

SELECT DISTINCT Category FROM Product ORDER BY Category WHERE Price

Exercise “WHERE” should always proceed “ORDER BY” SELECT DISTINCT Category FROM Product
< 1000

Product

Error!

Слайд 48

Exercise

SELECT DISTINCT Category FROM Product ORDER BY PName

Product

?

Exercise SELECT DISTINCT Category FROM Product ORDER BY PName Product ?

Слайд 49

Exercise

“ORDER BY” items must appear in the select list if “SELECT DISTINCT”

Exercise “ORDER BY” items must appear in the select list if “SELECT
is specified

SELECT DISTINCT Category FROM Product ORDER BY PName

Product

Error!

Слайд 50

Joins

Company

Product

A user wants to know the names and prices of all products

Joins Company Product A user wants to know the names and prices
by Japan companies. How?

Слайд 51

Joins

Company

Product

SELECT PName, Price FROM Product, Company WHERE Country = ‘Japan’ AND Manufacturer = CName

Joins Company Product SELECT PName, Price FROM Product, Company WHERE Country =

Слайд 52

Joins

Find the names of the persons who work for companies in USA
SELECT

Joins Find the names of the persons who work for companies in
PName FROM Person, Company WHERE Country = ‘USA’ AND WorksFor = CName

Company

Person

Слайд 53

Joins

Find the names the persons who work for companies in USA, as

Joins Find the names the persons who work for companies in USA,
well as their company addresses
SELECT PName, Address FROM Person, Company WHERE Country = ‘USA’ AND WorksFor = CName

Error!

Company

Person

Слайд 54

Joins

Company

Person

Find the names the persons who work for companies in USA, as

Joins Company Person Find the names the persons who work for companies
well as their company addresses
SELECT PName, Company.Address FROM Person, Company WHERE Country = ‘USA’ AND WorksFor = CName

Слайд 55

Joins

Find the names the persons who work for companies in USA, as

Joins Find the names the persons who work for companies in USA,
well as their company addresses
SELECT PName, Company.Address FROM Person, Company WHERE Country = ‘USA’ AND CName = CName

Error!

Company

Person

Слайд 56

Joins

Find the names the persons who work for companies in USA, as

Joins Find the names the persons who work for companies in USA,
well as their company addresses
SELECT PName, Company.Address FROM Person, Company WHERE Country = ‘USA’ AND Person.CName = Company.CName

Company

Person

Слайд 57

Joins

Find the names the persons who work for companies in USA, as

Joins Find the names the persons who work for companies in USA,
well as their company addresses
SELECT X.PName, Y.Address FROM Person AS X, Company AS Y WHERE Y.Country = ‘USA’ AND X.CName = Y.CName

Company

Person

Слайд 58

Joins

Find the names the persons who work for companies in USA, as

Joins Find the names the persons who work for companies in USA,
well as their company addresses
SELECT X.PName, Y.Address FROM Person X, Company Y WHERE Y.Country = ‘USA’ AND X.CName = Y.CName

Company

Person

Слайд 59

Exercise

Company

Product

Exercise: Find the names of the companies in China that produce products

Exercise Company Product Exercise: Find the names of the companies in China
in the ‘tablet’ category
SELECT DISTINCT CName FROM Company, Product WHERE Manufacturer = CName AND Country = ‘China’ AND Category = ‘Tablet’

Слайд 60

Exercise

Company

Product

Exercise: Find the names of the companies in China that produce products

Exercise Company Product Exercise: Find the names of the companies in China
in the ‘tablet’ or ‘phone’ category
SELECT DISTINCT CName FROM Company, Product WHERE Manufacturer = CName AND Country = ‘China’ AND (Category = ‘Tablet’ OR Category = ‘Phone’)

Слайд 61

Exercise

Exercise: Find the manufacturers that produce products in both the ‘tablet’ and

Exercise Exercise: Find the manufacturers that produce products in both the ‘tablet’
‘phone’ categories
SELECT DISTINCT Manufacturer FROM Product WHERE Category = ‘Tablet’ AND Category = ‘Phone’

Error!

Product

Слайд 62

Exercise

Product

Exercise: Find the manufacturers that produce products in both the ‘tablet’ and

Exercise Product Exercise: Find the manufacturers that produce products in both the
‘phone’ categories
SELECT DISTINCT X.Manufacturer FROM Product AS X, Product AS Y WHERE X.Manufacturer = Y.Manufacturer AND X.Category = ‘Tablet’ AND Y.Category = ‘Phone’

Слайд 63

Subqueries

A subquery is a SQL query nested inside a larger query
Queries with

Subqueries A subquery is a SQL query nested inside a larger query
subqueries are referred to as nested queries
A subquery may occur in
SELECT
FROM
WHERE

SQL subquery

SQL subquery

Слайд 64

A special subquery: Scalar Subquery

Example Query

From Sells(bar, beer, price), find the bars

A special subquery: Scalar Subquery Example Query From Sells(bar, beer, price), find
that serve Heineken for the same price Ku De Ta charges for Bud.

Scalar Subquery

return a single value which is then used in a comparison.
If query is written so that it expects a subquery to return a single value, and it returns multiple values or no values, a run-time error occurs.

Слайд 65

Example Scalar Subquery

SELECT price
FROM Sells
WHERE bar = `Ku De Ta’
AND beer =

Example Scalar Subquery SELECT price FROM Sells WHERE bar = `Ku De
`Bud’;

SELECT bar
FROM Sells
WHERE beer = `Heineken’
AND price = 7.90;

Sells

Find the price Ku De Ta charges for Bud.

Find the bars that serve Heineken at that price.

Слайд 66

Example Scalar Subquery

SELECT bar
FROM Sells
WHERE beer = ‘Heineken’ AND
price = (SELECT price

Example Scalar Subquery SELECT bar FROM Sells WHERE beer = ‘Heineken’ AND
FROM Sells
WHERE bar = ‘Ku De Ta’
AND beer = ‘Bud’);

Слайд 67

Subqueries in FROM

Find all products in the ‘phone’ category with prices under

Subqueries in FROM Find all products in the ‘phone’ category with prices
1000
SELECT X.PName FROM (SELECT * FROM Product WHERE category = ‘Phone’) AS X WHERE X.Price < 1000

Company

Product

Слайд 68

Subqueries in FROM (cont.)

Find all products in the ‘phone’ category with prices

Subqueries in FROM (cont.) Find all products in the ‘phone’ category with
under 1000
SELECT PName FROM Product WHERE Category = ‘Phone’ AND Price < 1000
This is a much more efficient solution

Company

Product

Слайд 69

Subqueries in WHERE (cont.)

Find all companies that make some products with price

Subqueries in WHERE (cont.) Find all companies that make some products with
< 100
SELECT DISTINCT CName FROM Company AS X WHERE X.CName IN
(SELECT Y.CName FROM Product AS Y
WHERE Y.Price < 100)

Company

Product

Слайд 70

Subqueries in WHERE (cont.)

Find all companies that make some products with price

Subqueries in WHERE (cont.) Find all companies that make some products with
< 100
SELECT DISTINCT CName FROM Company AS X WHERE EXISTS
(SELECT * FROM Product AS Y
WHERE X.CName = Y.Cname AND Y.Price < 100)

Company

Product

A nested query is correlated with the outer query if it contains a reference to an attribute in the outer query.
A nested query is correlated with the outside query if it must be re-computed for every tuple produced by the outside query.

Слайд 71

Subqueries in WHERE (cont.)

Find all companies that make some products with price

Subqueries in WHERE (cont.) Find all companies that make some products with
< 100
SELECT DISTINCT CName FROM Company AS X WHERE X.CName IN
(SELECT * FROM Product AS Y
WHERE Y.Price < 100)

Company

Product

Error!

The number of attributes in the SELECT clause in the subquery must match the number of attributes compared to with the comparison operator.

Слайд 72

Subqueries in WHERE (cont.)

Find all companies that make some products with price

Subqueries in WHERE (cont.) Find all companies that make some products with
< 100
SELECT DISTINCT CName FROM Company AS X WHERE 100 > ANY
(SELECT Price FROM Product AS Y
WHERE X.CName = Y.Cname)

Company

Product

Слайд 73

Subqueries in WHERE (cont.)

Find all companies that make some products with price

Subqueries in WHERE (cont.) Find all companies that make some products with
< 100
SELECT DISTINCT CName FROM Product WHERE Price < 100
This is more efficient than the previous solutions

Company

Product

Слайд 74

Operators in Subqueries

IN

IN is
true if and only if the
tuple

Operators in Subqueries IN IN is true if and only if the
is a member of the
relation.

EXISTS

EXISTS( ) is true if and only if the is not empty.
Returns true if the nested query has 1 or more tuples.

ANY

x = ANY( ) is a
boolean cond. meaning
that x equals at least one
tuple in the relation.

ALL

x <> ALL() is true if and only if for every tuple t in the relation, x is not equal to t.

Слайд 75

Avoiding Nested Queries

In general, nested queries tend to be more inefficient than

Avoiding Nested Queries In general, nested queries tend to be more inefficient
un-nested queries
query optimizers of DBMS do not generally do a good job at optimizing queries containing subqueries
Therefore, they should be avoided whenever possible
But there are cases where avoiding nested queries is hard…

Слайд 76

Subqueries in WHERE (cont.)

Find all companies that do not make any product

Subqueries in WHERE (cont.) Find all companies that do not make any
with price < 100
SELECT DISTINCT CName FROM Company AS X WHERE NOT EXISTS
(SELECT * FROM Product AS Y
WHERE X.CName = Y.Cname AND Y.Price < 100)

Company

Product

Слайд 77

Subqueries in WHERE (cont.)

Find all companies that do not make any product

Subqueries in WHERE (cont.) Find all companies that do not make any
with price < 100
SELECT DISTINCT CName FROM Company AS X WHERE 100 <= ALL
(SELECT Price FROM Product AS Y
WHERE X.CName = Y.Cname)

Company

Product

Слайд 78

Subqueries in WHERE (cont.)

Find all companies that does not make any products

Subqueries in WHERE (cont.) Find all companies that does not make any
with price < 100
SELECT DISTINCT CName FROM Company AS X WHERE 100 <= ALL
(SELECT Price FROM Product AS Y
WHERE X.CName = Y.Cname)

Company

Product

Слайд 79

Exercise

Find all drinkers that frequent some bar that serves some beer they

Exercise Find all drinkers that frequent some bar that serves some beer
like
SELECT DINSTINT F.Drinker FROM Likes AS L, Frequent AS F, Serve AS S WHERE L.Drinker = F.Drinker AND F.Bar = S.Bar AND L.Beer = S.Beer

Likes

Frequent

Serves

Слайд 80

Exercise

Find all drinkers that frequent some bar that does not serve any

Exercise Find all drinkers that frequent some bar that does not serve
beer they like
SELECT DISTINCT F.Drinker FROM Frequent AS F, Serves AS S WHERE F.Bar = S.Bar AND NOT EXIST (SELECT * FROM Likes as L WHERE L.Beer = S.Beer AND L.Drinker = F.Drinker)

Likes

Frequent

Serves

Слайд 81

Exercise

Find all drinkers that do not frequent any bar that serve some

Exercise Find all drinkers that do not frequent any bar that serve
beer they like
SELECT DISTINCT F.Drinker FROM Frequent AS F WHERE NOT EXIST (SELECT * FROM Likes AS L, Serves AS S WHERE L.Beer = S.Beer AND L.Drinker = F.Drinker AND S.Bar = F.Bar)

Likes

Frequent

Serves

Слайд 82

Roadmap --SQL

Table
SELECT FROM WHERE
ORDER BY
Joins
Subqueries
Aggregations
UNION, INTERSECT, EXCEPT
NULL
Outerjoin
Insert/Delete tuples
Create/Alter/Delete tables
View

Roadmap --SQL Table SELECT FROM WHERE ORDER BY Joins Subqueries Aggregations UNION,

Слайд 83

Exercise

Find all drinkers that frequent some bar that does not serve any

Exercise Find all drinkers that frequent some bar that does not serve
beer they like
SELECT DISTINCT F.Drinker FROM Frequent AS F
WHERE NOT EXIST (SELECT * FROM Serves as S, Likes as L WHERE L.Beer = S.Beer AND L.Drinker = F.Drinker
AND F.Bar = S.Bar)

Likes

Frequent

Serves

Имя файла: 3-Lect-Intro-SQL--updated.pptx
Количество просмотров: 25
Количество скачиваний: 0