You are on page 1of 108

IS 263/ IS 264

Lecture 5: SQL
Instructor: Henry Kalisti

Department of Computer Science and Engineering


DDL and DML
• DDL: Data Definition Language
• Changes data base schema
• Example: create table, drop table, alter table,
create index
• DML: Data Manipulation Language
• Read or change the content of the database
• Example: insert, delete, select, update

2
Data Definition Language
• May change:
• The schema for each relation.
• The domain of values associated with each
attribute.
• Integrity constraints
• The set of indices to be maintained for each
relations.
• Security and authorization information for
each relation.
• The physical storage structure of each 3

relation on disk.
Domain Types in SQL
• char(n). Fixed length character string, with user-
specified length n.
• varchar(n). Variable length character strings,
with user-specified maximum length n.
• int. Integer (a finite subset of the integers that is
machine-dependent).
• smallint. Small integer (a machine-dependent
subset of the integer domain type).
• numeric(p, d). Fixed point number, with user-
specified precision of p digits, with d digits to the
right of decimal point.
4
Domain Types in SQL
• real, double precision. Floating point and double-
precision floating point numbers, with machine-
dependent precision.
• float(n). Floating point number, with user-
specified precision of at least n digits.
• Null values are allowed in all the domain types.
Declaring an attribute to be not null prohibits null
values for that attribute.
• create domain construct in SQL-92 creates user-
defined domain types 5

• create domain person-name char(20) not null


Date/Time Types in SQL
• date. Dates, containing a (4 digit) year, month and
date
• E.g. date ‘2001-7-27’
• time. Time of day, in hours, minutes and seconds.
• E.g. time ’09:00:30’ time ’09:00:30.75’
• timestamp: date plus time of day
• E.g. timestamp ‘2001-7-27 09:00:30.75’
• Interval: period of time
• E.g. Interval ‘1’ day
• Subtracting a date/time/timestamp value from another
gives an interval value
• Interval values can be added to date/time/timestamp
values 6
Create Table Construct
• An SQL relation is defined using the create table
command:
create table r (A1 D1, A2 D2, ..., An Dn,
(integrity-constraint1),
...,
(integrity-constraintk))
• r is the name of the relation
• each Ai is an attribute name in the schema of
relation r
• Di is the data type of values in the domain of 7

attribute Ai
Integrity Constraints in Create Table
• not null
• primary key (A1, ..., An)
• Foreign Key (A,…,An) references s(B1,…Bn)
• check (P), where P is a predicate
Example: Declare branch-name as the primary key for branch and
ensure that the values of assets are non-negative.
create table branch
(branch-name char(15),
branch-city char(30)
assets integer,
primary key (branch-name),
check (assets >= 0))

primary key declaration on an attribute automatically ensures not 8

null in SQL-92 onwards, needs to be explicitly stated in SQL-89


Integrity Constraints in Create Table
• Foreign Key
Example: Declare branch-name in loan table
referencing the branch-name for branch
CREATE TABLE loan
( loan_number char(100),
branch_name char(15) REFERENCES branch(branch_name),
amount int,
PRIMARY KEY(loan_number) );

Foreign key means: loan.branch_name Í branch.branch_name


9
Drop and Alter Table
• The drop table command deletes all
information about the dropped relation from
the database.
• The alter table command is used to add
attributes to an existing relation.
alter table r add A D
where A is the name of the attribute to be
added to relation r and D is the domain of A.
• All tuples in the relation are assigned null as
the value for the new attribute.
10
Drop and Alter Table
• The alter table command can also be used to
drop attributes of a relation
alter table r drop A
where A is the name of an attribute of relation r
• However, dropping of attributes not
supported by many databases

11
DML
• Read or change the content of the database

12
Data in SQL
1. Atomic types, a.k.a. data types
2. Tables built from atomic types

13
Data Types in SQL
• Characters:
CHAR(20) -- fixed length
VARCHAR(40) -- variable length
• Numbers:
BIGINT, INT, SMALLINT, TINYINT
REAL, FLOAT -- differ in precision
MONEY
• Times and dates:
DATE
DATETIME -- SQL Server 14
• Others... All are simple
Tables in SQL Attribute names
Table name
Product

PName Price Category Manufacturer

Gizmo $19.99 Gadgets GizmoWorks

Powergizmo $29.99 Gadgets GizmoWorks

SingleTouch $149.99 Photography Canon

MultiTouch $203.99 Household Hitachi


15

Tuples or rows
Tables Explained
• A tuple = a record
• Restriction: all attributes are of atomic type
• A table = a set of tuples
• Like a list…
• …but it is unorderd: no first(), no next(), no
last().
• No nested tables, only flat tables are allowed !
• We will see later how to decompose complex
structures into multiple flat tables 16
Tables Explained
• The schema of a table is the table name and its
attributes:
• Product(PName, Price, Category, Manufacturer)

• A key is an attribute whose values are unique;


we underline a key
• Product(PName, Price, Category, Manufacturer)

17
SQL Query

Basic form: (plus many many more bells and whistles)

SELECT attributes
FROM relations (possibly multiple, joined)
WHERE conditions (selections)

18
Simple SQL Query
Product

PName Price Category Manufacturer


Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi

SELECT *
FROM Product
WHERE category=‘Gadgets’
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks 19
Powergizmo $29.99 Gadgets GizmoWorks
“selection”
Simple SQL Query
Product

PName Price Category Manufacturer


Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi

SELECT PName, Price, Manufacturer


FROM Product
WHERE Price > 100

PName Price Manufacturer


“selection” and SingleTouch $149.99 Canon 20
“projection” MultiTouch $203.99 Hitachi
A Notation for SQL Queries
Input Schema

Product(PName, Price, Category, Manfacturer)

SELECT PName, Price, Manufacturer


FROM Product
WHERE Price > 100

Answer(PName, Price, Manfacturer)


21

Output Schema
Selections
What goes in the WHERE clause:
• x = y, x < y, x <= y, etc
• For number, they have the usual meanings
• For CHAR and VARCHAR: lexicographic
ordering
• Expected conversion between CHAR and
VARCHAR
• For dates and times, what you expect...
• Pattern matching on strings: s LIKE p (next) 22
The LIKE operator
• s LIKE p: pattern matching on strings
• p may contain two special symbols:
• % = any sequence of characters
• _ = any single character

Product(Name, Price, Category, Manufacturer)


Find all products whose name mentions ‘gizmo’:
SELECT *
FROM Products 23
WHERE PName LIKE ‘%gizmo%’
Eliminating Duplicates
Category
Gadgets
SELECT category Gadgets
FROM Product Photography
Household

Compare to:

Category
SELECT DISTINCT category Gadgets
FROM Product Photography
Household
24
Ordering the Results

SELECT pname, price, manufacturer


FROM Product
WHERE category=‘gizmo’ AND price > 50
ORDER BY price, pname

Ordering is ascending, unless you specify the DESC


keyword.

Ties are broken by the second attribute on the 25


ORDER BY list, etc.
Ordering the Results

SELECT Category
FROM Product
ORDER BY PName

PName Price Category Manufacturer

?
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
26
Ordering the Results
Category
SELECT DISTINCT category Gadgets

FROM Product Household


Photography
ORDER BY category

Compare to:

?
SELECT DISTINCT category
FROM Product
ORDER BY PName
27
Joins in SQL
• Connect two or more tables:

Product PName Price Category Manufacturer


Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi

Company CName StockPrice Country

What is GizmoWorks 25 USA


the Connection Canon 65 Japan
28
between
them ? Hitachi 15 Japan
Joins
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)

Find all products under $200 manufactured in Japan;


return their names and prices.
Join
between Product
SELECT PName, Price and Company
FROM Product, Company
WHERE Manufacturer=CName AND Country=‘Japan’
AND Price <= 200
29
Joins in SQL
Product
Company

PName Price Category Manufacturer Cname StockPrice Country


Gizmo $19.99 Gadgets GizmoWorks GizmoWorks 25 USA
Powergizmo $29.99 Gadgets GizmoWorks Canon 65 Japan
SingleTouch $149.99 Photography Canon Hitachi 15 Japan
MultiTouch $203.99 Household Hitachi

SELECT PName, Price


FROM Product, Company
WHERE Manufacturer=CName AND Country=‘Japan’
AND Price <= 200

PName Price
30
SingleTouch $149.99
Joins
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)

Find all countries that manufacture some product in the


‘Gadgets’ category.

SELECT Country
FROM Product, Company
WHERE Manufacturer=CName AND Category=‘Gadgets’

31
Joins in SQL
Product
Company
PName Price Category Manufacturer
Cname StockPrice Country
Gizmo $19.99 Gadgets GizmoWorks
GizmoWorks 25 USA
Powergizmo $29.99 Gadgets GizmoWorks
Canon 65 Japan
SingleTouch $149.99 Photography Canon
Hitachi 15 Japan
MultiTouch $203.99 Household Hitachi

SELECT Country
FROM Product, Company
WHERE Manufacturer=CName AND Category=‘Gadgets’

Country
What is ??
the problem ? ?? 32
What’s the
solution ?
Joins
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

SELECT DISTINCT persname, store


FROM Person, Purchase, Product
WHERE persname=buyer AND product = pname AND 33

city=‘Seattle’ AND category=‘Gadgets’


Disambiguating Attributes
• Sometimes two relations have the same attr:
Person(pname, address, worksfor)
Company(cname, address)

Which
SELECT DISTINCT pname, address address ?
FROM Person, Company
WHERE worksfor = cname

SELECT DISTINCT Person.pname, Company.address 34


FROM Person, Company
WHERE Person.worksfor = Company.cname
Tuple Variables
Product (pname, price, category, manufacturer)
Purchase (buyer, seller, store, product)
Person(persname, phoneNumber, city)
Find all stores that sold at least one product that the store
‘BestBuy’ also sold:

SELECT DISTINCT x.store


FROM Purchase AS x, Purchase AS y
WHERE x.product = y.product AND y.store = ‘BestBuy’

35

Answer (store)
Tuple Variables
General rule:
tuple variables introduced automatically by the system:

Product ( name, price, category, manufacturer)


SELECT name
FROM Product
WHERE price > 100
Becomes:

SELECT Product.name
FROM Product AS Product
WHERE Product.price > 100
36
Doesn’t work when Product occurs more than once:
In that case the user needs to define variables explicitely.
Renaming Columns
Product PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi

SELECT Pname AS prodName, Price AS askPrice


FROM Product
WHERE Price > 100
prodName askPrice

Query with SingleTouch $149.99


37
MultiTouch $203.99
renaming
Meaning (Semantics) of SQL
Queries
SELECT a1, a2, …, ak
FROM R1 AS x1, R2 AS x2, …, Rn AS xn
WHERE Conditions

1. Nested loops:

Answer = {}
for x1 in R1 do
for x2 in R2 do
…..
for xn in Rn do
if Conditions 38
then Answer = Answer È {(x1,…,xk)}
return Answer
Meaning (Semantics) of SQL
Queries
SELECT a1, a2, …, ak
FROM R1 AS x1, R2 AS x2, …, Rn AS xn
WHERE Conditions

2. Parallel assignment

Answer = {}
for all assignments x1 in R1, …, xn in Rn do
if Conditions then Answer = Answer È {(x1,…,xk)}
return Answer

Doesn’t impose any order ! 39


First Unintuitive SQLism
SELECT R.A
FROM R, S, T
WHERE R.A=S.A OR R.A=T.A

Looking for R Ç (S È T)

But what happens if T is empty?

40
Advanced SQL

Part 2

41
Outline

• Unions, intersections, differences


• Subqueries, Aggregations, NULLs
• Modifying databases, Indexes, Views

42
Union, Intersection, Difference
(SELECT name
FROM Person
WHERE City=“Seattle”)

UNION

(SELECT name
FROM Person, Purchase
WHERE buyer=name AND store=“The Bon”)

43
Similarly, you can use INTERSECT and EXCEPT.
You must have the same attribute names (otherwise: rename).
Conserving Duplicates

(SELECT name
FROM Person
WHERE City=“Seattle”)

UNION ALL

(SELECT name
FROM Person, Purchase
WHERE buyer=name AND store=“The Bon”) 44
Subqueries

A subquery producing a single value:


SELECT Purchase.product
FROM Purchase
WHERE buyer =
(SELECT name
FROM Person
WHERE ssn = ‘123456789‘);

In this case, the subquery returns one value.

If it returns more, it’s a run-time error. 45


Subqueries

Can say the same thing without a subquery:

SELECT Purchase.product
FROM Purchase, Person
WHERE buyer = name AND ssn = ‘123456789‘
This is equivalent to the previous one when the ssn is a key
and ‘123456789’ exists in the database;
otherwise they are different.

46
Subqueries Returning
Relations
Find companies that manufacture products bought by Joe Blow.
SELECT Company.name
FROM Company, Product
WHERE Company.name = Product.maker
AND Product.name IN
(SELECT Purchase.product
FROM Purchase
WHERE Purchase .buyer = ‘Joe Blow‘);

47
Here the subquery returns a set of values: no more
runtime errors.
Subqueries Returning
Relations
Equivalent to:
SELECT Company.name
FROM Company, Product, Purchase
WHERE Company.name = Product.maker
AND Product.name = Purchase.product
AND Purchase.buyer = ‘Joe Blow’

Is this query equivalent to the previous one ?


48
Beware of duplicates !
Removing Duplicates
SELECT DISTINCT Company.name
FROM Company, Product
WHERE Company.name= Product.maker
AND Product.name IN
(SELECT Purchase.product
FROM Purchase
WHERE Purchase.buyer = ‘Joe Blow’)

SELECT DISTINCT Company.name


Now
FROM Company, Product, Purchase
they are
WHERE Company.name= Product.maker
equivalent 49
AND Product.name = Purchase.product
AND Purchase.buyer = ‘Joe Blow’
Subqueries Returning
Relations
You can also use: s > ALL R
s > ANY R
EXISTS R
Product ( pname, price, category, maker)
Find products that are more expensive than all those produced
By “Gizmo-Works”

SELECT name
FROM Product
WHERE price > ALL (SELECT price
FROM Purchase 50

WHERE maker=‘Gizmo-Works’)
Correlated Queries
Movie (title, year, director, length)
Find movies whose title appears more than once.
correlation

SELECT DISTINCT title


FROM Movie AS x
WHERE year < > ANY
(SELECT year
FROM Movie
WHERE title = x.title);
51

Note (1) scope of variables (2) this can still be expressed as


single SFW
Complex Correlated Query

Product ( pname, price, category, maker, year)


• Find products (and their manufacturers) that are more expensive
than all products made by the same manufacturer before 1972

SELECT DISTINCT pname, maker


FROM Product AS x
WHERE price > ALL (SELECT price
FROM Product AS y
WHERE x.maker = y.maker AND y.year < 1972);

Powerful, but much harder to optimize !


52
Existential/Universal
Conditions
Product ( pname, price, company)
Company( cname, city)

Find all companies s.t. some of their products have price < 100

SELECT DISTINCT Company.cname


FROM Company, Product
WHERE Company.cname = Product.company and Product.price < 100

53

Existential: easy ! J
Existential/Universal
Conditions
Product ( pname, price, company)
Company( cname, city)

Find all companies s.t. all of their products have price < 100

Universal: hard ! L

54
Existential/Universal
Conditions
1. Find the other companies: i.e. s.t. some product ³ 100
SELECT DISTINCT Company.cname
FROM Company
WHERE Company.cname IN (SELECT Product.company
FROM Product
WHERE Product.price >= 100

2. Find all companies s.t. all their products have price < 100
SELECT DISTINCT Company.cname
FROM Company
WHERE Company.cname NOT IN (SELECT Product.company
55
FROM Product
WHERE Product.price >= 100
Aggregation

SELECT Avg(price)
FROM Product
WHERE maker=“Toyota”

SQL supports several aggregation operations:

SUM, MIN, MAX, AVG, COUNT

56
Aggregation: Count

SELECT Count(*)
FROM Product
WHERE year > 1995

Except COUNT, all aggregations apply to a single attribute


57
Aggregation: Count

COUNT applies to duplicates, unless otherwise stated:

SELECT Count(category) same as Count(*)


FROM Product
WHERE year > 1995

Better:

SELECT Count(DISTINCT category)


FROM Product 58

WHERE year > 1995


Simple Aggregation

Purchase(product, date, price, quantity)

Example 1: find total sales for the entire database

SELECT Sum(price * quantity)


FROM Purchase

Example 1’: find total sales of bagels

SELECT Sum(price * quantity)


FROM Purchase 59

WHERE product = ‘bagel’


Simple Aggregations
Purchase
Product Date Price Quantity
Bagel 10/21 0.85 15
Banana 10/22 0.52 7
Banana 10/19 0.52 17
Bagel 10/20 0.85 20
60
Grouping and Aggregation
Usually, we want aggregations on certain parts of the relation.

Purchase(product, date, price, quantity)

Example 2: find total sales after 9/1 per product.

SELECT product, Sum(price*quantity) AS TotalSales


FROM Purchase
WHERE date > “9/1”
GROUP BY product
61

Let’s see what this means…


Grouping and Aggregation

1. Compute the FROM and WHERE clauses.


2. Group by the attributes in the GROUP BY
3. Produce one tuple for every group by applying aggregation

SELECT can have (1) grouped attributes or (2) aggregates.

62
First compute the FROM-WHERE clauses (date >
“9/1”) then GROUP BY product:

Product Date Price Quantity


Banana 10/19 0.52 17
Banana 10/22 0.52 7
Bagel 10/20 0.85 20
Bagel 10/21 0.85 15

63
Then, aggregate
Product TotalSales

Bagel $29.75

Banana $12.48

SELECT product, Sum(price*quantity) AS TotalSales


FROM Purchase
WHERE date > “9/1” 64
GROUP BY product
GROUP BY v.s. Nested Quereis
SELECT product, Sum(price*quantity) AS TotalSales
FROM Purchase
WHERE date > “9/1”
GROUP BY product

SELECT DISTINCT x.product, (SELECT Sum(y.price*y.quantity)


FROM Purchase y
WHERE x.product = y.product
AND y.date > ‘9/1’)
AS TotalSales
FROM Purchase x
65
WHERE x.date > “9/1”
Another Example
Product SumSales MaxQuantity

Banana $12.48 17

Bagel $29.75 20

For every product, what is the total sales and max quantity sold?
SELECT product, Sum(price * quantity) AS SumSales
Max(quantity) AS MaxQuantity
66
FROM Purchase
GROUP BY product
HAVING Clause

Same query, except that we consider only products that had


at least 30 items sold.

SELECT product, Sum(price * quantity)


FROM Purchase
WHERE date > “9/1”
GROUP BY product
HAVING Sum(quantity) > 30

HAVING clause contains conditions on aggregates. 67


General form of Grouping and
Aggregation
SELECT S
FROM R1,…,Rn
WHERE C1
GROUP BY a1,…,ak
HAVING C2 Why ?

S = may contain attributes a1,…,ak and/or any aggregates but NO


OTHER ATTRIBUTES
C1 = is any condition on the attributes in R1,…,Rn
C2 = is any condition on aggregate expressions

68
General form of Grouping and
Aggregation
SELECT S
FROM R1,…,Rn
WHERE C1
GROUP BY a1,…,ak
HAVING C2

Evaluation steps:
1. Compute the FROM-WHERE part, obtain a table with all attributes in
R1,…,Rn
2. Group by the attributes a1,…,ak
3. Compute the aggregates in C2 and keep only groups satisfying C2
4. Compute aggregates in S and return the result 69
Aggregation
Author(login,name)
Document(url, title)
Wrote(login,url)
Mentions(url,word)

70
Grouping vs. Nested Queries
• Find all authors who wrote at least 10 documents:
• Attempt 1: with nested queries

This is
SQL by
a novice
SELECT DISTINCT Author.name
FROM Author
WHERE count(SELECT Wrote.url
FROM Wrote
WHERE Author.login=Wrote.login) 71

> 10
Grouping vs. Nested Queries
• Find all authors who wrote at least 10 documents:
• Attempt 2: SQL style (with GROUP BY)

SELECT Author.name This is


FROM Author, Wrote SQL by
WHERE Author.login=Wrote.login an expert
GROUP BY Author.name
HAVING count(wrote.url) > 10 72

No need for DISTINCT: automatically from GROUP BY


Grouping vs. Nested Queries
• Find all authors who have a vocabulary over 10000 words:

SELECT Author.name
FROM Author, Wrote, Mentions
WHERE Author.login=Wrote.login AND Wrote.url=Mentions.url
GROUP BY Author.name
HAVING count(distinct Mentions.word) > 10000

Look carefully at the last two queries: you may 73

be tempted to write them as a nested queries,


but in SQL we write them best with GROUP BY
NULLS in SQL
• Whenever we don’t have a value, we can put a NULL
• Can mean many things:
• Value does not exists
• Value exists but is unknown
• Value not applicable
• Etc.
• The schema specifies for each attribute if it can be null
(nullable attribute) or not
• How does SQL cope with tables that have NULLs ?

74
Null Values
• If x= NULL then 4*(3-x)/7 is still NULL

• If x= NULL then x=“Joe” is UNKNOWN


• In SQL there are three boolean values:
FALSE = 0
UNKNOWN = 0.5
TRUE = 1

75
Null Values
• C1 AND C2 = min(C1, C2)
• C1 OR C2 = max(C1, C2)
• NOT C1 = 1 – C1

SELECT * E.g.
FROM Person age=20
WHERE (age < 25) AND heigth=NULL
weight=200
(height > 6 OR weight > 190)
Rule in SQL: include only tuples that yield TRUE
76
Null Values
Unexpected behavior:

SELECT *
FROM Person
WHERE
Some Persons age <included
are not 25 OR! age >= 25

77
Null Values
Can test for NULL explicitly:
• x IS NULL
• x IS NOT NULL

SELECT *
FROM Person
WHERE age < 25 OR age >= 25 OR age IS NULL

Now it includes all Persons


78
Outerjoins
Explicit joins in SQL:
Product(name, category)
Purchase(prodName, store)

SELECT Product.name, Purchase.store


FROM Product JOIN Purchase ON
Product.name = Purchase.prodName

Same as:
But Products that never sold will be lost !
SELECT Product.name, Purchase.store
FROM Product, Purchase
WHERE Product.name = Purchase.prodName 79
Outerjoins
Left outer joins in SQL:
Product(name, category)
Purchase(prodName, store)

SELECT Product.name, Purchase.store


FROM Product LEFT OUTER JOIN Purchase ON
Product.name = Purchase.prodName

80
Product Purchase
Name Category ProdName Store

Gizmo gadget Gizmo Wiz

Camera Photo Camera Ritz

OneClick Photo Camera Wiz

Name Store

Gizmo Wiz

Camera Ritz

Camera Wiz 81

OneClick NULL
Outer Joins

• Left outer join:


• Include the left tuple even if there’s no match
• Right outer join:
• Include the right tuple even if there’s no match
• Full outer join:
• Include the both left and right tuples even if there’s no match

82
Modifying the Database
Three kinds of modifications
• Insertions
• Deletions
• Updates

Sometimes they are all called “updates”

83
Insertions
General form:

INSERT INTO R(A1,…., An) VALUES (v1,…., vn)

Example: Insert a new purchase to the database:


INSERT INTO Purchase(buyer, seller, product, store)
VALUES (‘Joe’, ‘Fred’, ‘wakeup-clock-espresso-machine’,
‘The Sharper Image’)

Missing attribute ® NULL.


84

May drop attribute names if give them in order.


Insertions

INSERT INTO PRODUCT(name)

SELECT DISTINCT Purchase.product


FROM Purchase
WHERE Purchase.date > “10/26/01”

The query replaces the VALUES keyword.


Here we insert many tuples into PRODUCT 85
Insertion: an Example
Product(name, listPrice, category)
Purchase(prodName, buyerName, price)
prodName is foreign key in Product.name

Suppose database got corrupted and we need to fix it:


corrupted Purchase
Product
prodName buyerName price
name listPrice category
camera John 200

gizmo 100 gadgets gizmo Smith 80

camera Smith 225 86

Task: insert in Product all prodNames from Purchase


Insertion: an Example
INSERT INTO Product(name)

SELECT DISTINCT prodName


FROM Purchase
WHERE prodName NOT IN (SELECT name FROM Product)

name listPrice category

gizmo 100 Gadgets

camera - - 87
Insertion: an Example

INSERT INTO Product(name, listPrice)

SELECT DISTINCT prodName, price


FROM Purchase
WHERE prodName NOT IN (SELECT name FROM Product)

name listPrice category

gizmo 100 Gadgets

camera 200 -
88

camera ?? 225 ?? - Depends on the implementation


Deletions
Example:

DELETE FROM PURCHASE

WHERE seller = ‘Joe’ AND


product = ‘Brooklyn Bridge’

Factoid about SQL: there is no way to delete only a single


occurrence of a tuple that appears twice
in a relation. 89
Updates
Example:

UPDATE PRODUCT
SET price = price/2
WHERE Product.name IN
(SELECT product
FROM Purchase
WHERE Date =‘Oct, 25, 1999’);

90
Data Definition in SQL
So far we have seen the Data Manipulation Language, DML
Next: Data Definition Language (DDL)

Data types:
Defines the types.

Data definition: defining the schema.

• Create tables
• Delete tables
• Modify table schema
91

Indexes: to improve performance


Data Types in SQL

• Characters:
• CHAR(20) -- fixed length
• VARCHAR(40) -- variable length
• Numbers:
• INT, REAL plus variations
• Times and dates:
• DATE, TIME (Pointbase)

92
Creating Tables
Example:

CREATE TABLE Person(

name VARCHAR(30),
social-security-number INT,
age SHORTINT,
city VARCHAR(30),
gender BIT(1),
Birthdate DATE

); 93
Deleting or Modifying a Table
Deleting:
Example: DROP Person; Exercise with care !!

Altering: (adding or removing an attribute).

ALTER TABLE Person


ADD phone CHAR(16);
Example:
ALTER TABLE Person
DROP age;
94
What happens when you make changes to the schema?
Default Values

Specifying default values:

CREATE TABLE Person(


name VARCHAR(30),
social-security-number INT,
age SHORTINT DEFAULT 100,
city VARCHAR(30) DEFAULT ‘Seattle’,
gender CHAR(1) DEFAULT ‘?’,
Birthdate DATE

95

The default of defaults: NULL


Indexes
REALLY important to speed up query processing time.

Suppose we have a relation

Person (name, age, city)

SELECT *
FROM Person
WHERE name = “Smith”

96
Sequential scan of the file Person may take long
Indexes

• Create an index on name:

Adam Betty Charles …. Smith ….

• B+ trees have fan-out of 100s: max 4 levels !


97
Creating Indexes

Syntax:

CREATE INDEX nameIndex ON Person(name)

98
Creating Indexes

Indexes can be useful in range queries too:

CREATE INDEX ageIndex ON Person (age)

B+ trees help in: SELECT *


FROM Person
WHERE age > 25 AND age < 28
99
Why not create indexes on everything?
Creating Indexes
Indexes can be created on more than one attribute:

CREATE INDEX doubleindex ON


Example:
Person (age, city)

SELECT *
Helps in: FROM Person
WHERE age = 55 AND city = “Seattle”

SELECT *
and even in: FROM Person
WHERE age = 55

SELECT * 100
But not in: FROM Person
WHERE city = “Seattle”
The Index Selection Problem
• We are given a workload = a set of SQL queries
plus how often they run
• What indexes should we build to speed up the
workload ?
• FROM/WHERE clauses è favor an index
• INSERT/UPDATE clauses è discourage an index
• Index selection = normally done by people,
recently done automatically

101
Defining Views
Views are relations, except that they are not physically stored.

For presenting different information to different users

Employee(ssn, name, department, project, salary)

CREATE VIEW Developers AS


SELECT name, project
FROM Employee
WHERE department = “Development”
102
Payroll has access to Employee, others only to Developers
A Different View
Person(name, city)
Purchase(buyer, seller, product, store)
Product(name, maker, category)

CREATE VIEW Seattle-view AS

SELECT buyer, seller, product, store


FROM Person, Purchase
WHERE Person.city = “Seattle” AND
Person.name = Purchase.buyer

We have a new virtual table: 103

Seattle-view(buyer, seller, product, store)


A Different View

We can later use the view:

SELECT name, store


FROM Seattle-view, Product
WHERE Seattle-view.product = Product.name AND
Product.category = “shoes”

104
What Happens When We Query a
View ?
SELECT name, Seattle-view.store
FROM Seattle-view, Product
WHERE Seattle-view.product = Product.name AND
Product.category = “shoes”

SELECT name, Purchase.store


FROM Person, Purchase, Product
WHERE Person.city = “Seattle” AND
Person.name = Purchase.buyer AND
105
Purchase.poduct = Product.name AND
Product.category = “shoes”
Types of Views
• Virtual views:
• Used in databases
• Computed only on-demand – slow at runtime
• Always up to date
• Materialized views
• Used in data warehouses
• Pre-computed offline – fast at runtime
• May have stale data

106
Updating Views
How can I insert a tuple into a table that doesn’t exist?

Employee(ssn, name, department, project, salary)

CREATE VIEW Developers AS


SELECT name, project
FROM Employee
WHERE department = “Development”

If we make the INSERT INTO Developers


following insertion: VALUES(“Joe”, “Optimizer”)

It becomes: INSERT INTO Employee(ssn, name, department, project, salary)


VALUES(NULL, “Joe”, NULL, “Optimizer”, NULL) 107
Non-Updatable Views
Person(name, city)
Purchase(buyer, seller, product, store)
CREATE VIEW City-Store AS

SELECT Person.city, Purchase.store


FROM Person, Purchase
WHERE Person.name = Purchase.buyer

How can we add the following tuple to the view?

(“Seattle”, “Nine West”)


108
We don’t know the name of the person who made the purchase;
cannot set to NULL (why ?)

You might also like