SlideShare a Scribd company logo
1 of 90
SQL
• SQL is a database computer language designed for the
retrieval and management of data in a relational
database. SQL stands for Structured Query Language.
• SQL is used to communicate with a database.
• According to ANSI (American National Standards
Institute), it is the standard language for relational
database management systems. SQL statements are used
to perform tasks such as update data on a database, or
retrieve data from a database. Some common relational
database management systems that use SQL are: Oracle,
Sybase, Microsoft SQL Server, Access, Ingres, etc.
SQL Conti…
• As the name suggests, it is used when we have structured
data (in the form of tables). All databases that are not
relational (or do not use fixed structure tables to store
data) and therefore do not use SQL, are called NoSQL
databases. Examples of NoSQL are MongoDB,
DynamoDB, Cassandra, Hadoop etc
SQL Conti…
• SQL is case insensitive. But it is a recommended practice
to use keywords (like SELECT, UPDATE, CREATE, etc)
in capital letters and use user defined things (liked table
name, column name, etc) in small letters.
• We can write comments in SQL using “–” (double
hyphen) at the beginning of any line.
SQL Conti…
• SQL is the programming language for relational
databases (explained below) like MySQL, Oracle,
Sybase, SQL Server, Postgre, etc. Other non-
relational databases (also called NoSQL) databases
like MongoDB, DynamoDB, etc do not use SQL
• Although there is an ISO standard for SQL, most of
the implementations slightly vary in syntax. So we
may encounter queries that work in SQL Server but
do not work in MySQL, Oracle etc.
SQL Conti…
SQL Conti…
SQL Conti…
About IEC
SQL History
• IBM Sequel language developed as part of System
R project at the IBM San Jose Research Laboratory
• Renamed Structured Query Language (SQL)
• ANSI and ISO standard SQL:
– SQL-86
– SQL-89
– SQL-92
– SQL:1999
– SQL:2003
Tables in SQL
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
Product
Attribute names
Table name
Tuples or rows
Tables Explained
• The schema of a table is the table name and
its attributes:
Product(PName, Price, Category, Manfacturer)
• A key is an attribute whose values are unique;
we underline a key
Product(PName, Price, Category, Manfacturer)
Tables Explained
• SQL> create table students
• 2 (
• 3 roll int not null,
• 4 name varchar2(30) not null,
• 5 address varchar2(50) not null,
• 6 contact int not null
• 7 )
• 8 /
• Table created.
• SQL>
Tables Explained
• SQL> insert into students
• 2 values(120, 'Sachin', 'Mumbai',2465218);
• 1 row created.
Tables Explained
• SQL> insert into students
• 2 values(234, 'Rahul', 'Bengluru',222222);
• 1 row created.
• SQL> insert into students
• 2 values(111, 'Saurav Ganguly', 'Kolkata',3333);
• 1 row created.
Tables Explained
• SQL> insert into students
• 2 values(345, 'Mayank Agrawal', 'Mathura',7777777);
• 1 row created.
• SQL> insert into students
• 2 values(120, 'Deepak Chahar', 'Agra',99999);
• 1 row created.
Set Linesize
• SQL> show linesize
• linesize 80
• SQL> set linesize 150
• SQL> show linesize
• linesize 150
Set Pagesize
• SQL> show pagesiz
• pagesize 14
• SQL> set pagesize 50
• SQL> show pagesize
• pagesize 50
Set Pagesize
• SQL> set linesize 70
• SQL> select * from students;
• SQL> select * from students
• 2 where roll=120;
Tables Explained
• A table = a set of tuples
SQL Query
SELECT <attributes>
FROM <one or more relations>
WHERE <conditions>
Simple SQL Query
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’
Product
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
“selection”
Simple SQL Query
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
Product
PName Price Manufacturer
SingleTouch $149.99 Canon
MultiTouch $203.99 Hitachi
“selection” and
“projection”
Notation
Product(PName, Price, Category, Manfacturer)
Answer(PName, Price, Manfacturer)
Input Schema
Output Schema
SELECT PName, Price, Manufacturer
FROM Product
WHERE Price > 100
Details
• Case insensitive:
– Same: SELECT Select select
– Same: Product product
– Different: ‘Seattle’ ‘seattle’
• Constants:
– ‘abc’ - yes
– “abc” - no
The LIKE operator
• s LIKE p: pattern matching on strings
• p may contain two special symbols:
– % = any sequence of characters
– _ = any single character
SELECT *
FROM Products
WHERE PName LIKE ‘%gizmo%’
Eliminating Duplicates
SELECT DISTINCT category
FROM Product
Compare to:
SELECT category
FROM Product
Category
Gadgets
Gadgets
Photography
Household
Category
Gadgets
Photography
Household
Ordering the Results
SELECT pname, price, manufacturer
FROM Product
WHERE category=‘gizmo’AND price > 50
ORDER BY price, pname
Ties are broken by the second attribute on the ORDER BY list, etc.
Ordering is ascending, unless you specify the DESC keyword.
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
?
SELECT DISTINCT category
FROM Product
ORDER BY category
SELECT DISTINCT category
FROM Product
ORDER BY PName
?
?
Keys and Foreign Keys
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
Product
Company
CName StockPrice Country
GizmoWorks 25 USA
Canon 65 Japan
Hitachi 15 Japan
Key
Foreign
key
Joins
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)
Find all products under $200 manufactured in Japan;
return their names and prices.
SELECT PName, Price
FROM Product, Company
WHERE Manufacturer=CName AND Country=‘Japan’
AND Price <= 200
Join
between Product
and Company
Joins
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
Product
Company
Cname StockPrice Country
GizmoWorks 25 USA
Canon 65 Japan
Hitachi 15 Japan
PName Price
SingleTouch $149.99
SELECT PName, Price
FROM Product, Company
WHERE Manufacturer=CName AND Country=‘Japan’
AND Price <= 200
More Joins
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)
Find all Chinese companies that manufacture products
both in the ‘electronic’ and ‘toy’ categories
SELECT cname
FROM
WHERE
A Subtlety about 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’
Unexpected duplicates
A Subtlety about Joins
Name Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
Product
Company
Cname StockPrice Country
GizmoWorks 25 USA
Canon 65 Japan
Hitachi 15 Japan
Country
??
??
What is
the problem ?
What’s the
solution ?
SELECT Country
FROM Product, Company
WHERE Manufacturer=CName AND Category=‘Gadgets’
Tuple Variables
SELECT DISTINCT pname, address
FROM Person, Company
WHERE worksfor = cname
Which
address ?
Person(pname, address, worksfor)
Company(cname, address)
SELECT DISTINCT Person.pname, Company.address
FROM Person, Company
WHERE Person.worksfor = Company.cname
SELECT DISTINCT x.pname, y.address
FROM Person AS x, Company AS y
WHERE x.worksfor = y.cname
Meaning (Semantics) of SQL
Queries
SELECT a1, a2, …, ak
FROM R1 AS x1, R2 AS x2, …, Rn AS xn
WHERE Conditions
Answer = {}
for x1 in R1 do
for x2 in R2 do
…..
for xn in Rn do
if Conditions
then Answer = Answer  {(a1,…,ak)}
return Answer
SELECT DISTINCT R.A
FROM R, S, T
WHERE R.A=S.A OR R.A=T.A
An Unintuitive Query
Computes R  (S  T) But what if S = f ?
What does it compute ?
Subqueries Returning Relations
SELECT Company.city
FROM Company
WHERE Company.name IN
(SELECT Product.maker
FROM Purchase , Product
WHERE Product.pname=Purchase.product
AND Purchase .buyer = ‘Joe Blow‘);
Return cities where one can find companies that manufacture
products bought by Joe Blow
Company(name, city)
Product(pname, maker)
Purchase(id, product, buyer)
Subqueries Returning Relations
SELECT Company.city
FROM Company, Product, Purchase
WHERE Company.name= Product.maker
AND Product.pname = Purchase.product
AND Purchase.buyer = ‘Joe Blow’
Is it equivalent to this ?
Beware of duplicates !
Removing Duplicates
Now
they are
equivalent
SELECT DISTINCT Company.city
FROM Company
WHERE Company.name IN
(SELECT Product.maker
FROM Purchase , Product
WHERE Product.pname=Purchase.product
AND Purchase .buyer = ‘Joe Blow‘);
SELECT DISTINCT Company.city
FROM Company, Product, Purchase
WHERE Company.name= Product.maker
AND Product.pname = Purchase.product
AND Purchase.buyer = ‘Joe Blow’
Subqueries Returning Relations
SELECT name
FROM Product
WHERE price > ALL (SELECT price
FROM Purchase
WHERE maker=‘Gizmo-Works’)
Product ( pname, price, category, maker)
Find products that are more expensive than all those produced
By “Gizmo-Works”
You can also use: s > ALL R
s > ANY R
EXISTS R
Question for Database Fans
and their Friends
• Can we express this query as a single
SELECT-FROM-WHERE query, without
subqueries ?
Question for Database Fans
and their Friends
• Answer: all SFW queries are
monotone (figure out what this means).
A query with ALL is not monotone
Correlated Queries
SELECT DISTINCT title
FROM Movie AS x
WHERE year <> ANY
(SELECT year
FROM Movie
WHERE title = x.title);
Movie (title, year, director, length)
Find movies whose title appears more than once.
Note (1) scope of variables (2) this can still be expressed as single SFW
correlation
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
Very powerful ! Also much harder to optimize.
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);
Aggregation
SELECT count(*)
FROM Product
WHERE year > 1995
Except count, all aggregations apply to a single attribute
SELECT avg(price)
FROM Product
WHERE maker=“Toyota”
SQL supports several aggregation operations:
sum, count, min, max, avg
COUNT applies to duplicates, unless otherwise stated:
SELECT Count(category)
FROM Product
WHERE year > 1995
same as Count(*)
We probably want:
SELECT Count(DISTINCT category)
FROM Product
WHERE year > 1995
Aggregation: Count
Purchase(product, date, price, quantity)
More Examples
SELECT Sum(price * quantity)
FROM Purchase
SELECT Sum(price * quantity)
FROM Purchase
WHERE product = ‘bagel’
What do
they mean ?
Simple Aggregations
Purchase
Product Date Price Quantity
Bagel 10/21 1 20
Banana 10/3 0.5 10
Banana 10/10 1 10
Bagel 10/25 1.50 20
SELECT Sum(price * quantity)
FROM Purchase
WHERE product = ‘bagel’
50 (= 20+30)
Grouping and Aggregation
Purchase(product, date, price, quantity)
SELECT product, Sum(price*quantity) AS TotalSales
FROM Purchase
WHERE date > ‘10/1/2005’
GROUP BY product
Let’s see what this means…
Find total sales after 10/1/2005 per product.
Grouping and Aggregation
1. Compute the FROM and WHERE clauses.
2. Group by the attributes in the GROUPBY
3. Compute the SELECT clause: grouped attributes and aggregates.
1&2. FROM-WHERE-GROUPBY
Product Date Price Quantity
Bagel 10/21 1 20
Bagel 10/25 1.50 20
Banana 10/3 0.5 10
Banana 10/10 1 10
3. SELECT
SELECT product, Sum(price*quantity) AS TotalSales
FROM Purchase
WHERE date > ‘10/1/2005’
GROUP BY product
Product Date Price Quantity
Bagel 10/21 1 20
Bagel 10/25 1.50 20
Banana 10/3 0.5 10
Banana 10/10 1 10
Product TotalSales
Bagel 50
Banana 15
GROUP BY v.s. Nested Quereis
SELECT product, Sum(price*quantity) AS TotalSales
FROM Purchase
WHERE date > ‘10/1/2005’
GROUP BY product
SELECT DISTINCT x.product, (SELECT Sum(y.price*y.quantity)
FROM Purchase y
WHERE x.product = y.product
AND y.date > ‘10/1/2005’)
AS TotalSales
FROM Purchase x
WHERE x.date > ‘10/1/2005’
Another Example
SELECT product,
sum(price * quantity) AS SumSales
max(quantity) AS MaxQuantity
FROM Purchase
GROUP BY product
What does
it mean ?
HAVING Clause
SELECT product, Sum(price * quantity)
FROM Purchase
WHERE date > ‘10/1/2005’
GROUP BY product
HAVING Sum(quantity) > 30
Same query, except that we consider only products that had
at least 100 buyers.
HAVING clause contains conditions on aggregates.
General form of Grouping and
Aggregation
SELECT S
FROM R1,…,Rn
WHERE C1
GROUP BY a1,…,ak
HAVING C2
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
Why ?
General form of Grouping and
Aggregation
Evaluation steps:
1. Evaluate FROM-WHERE, apply condition C1
2. Group by the attributes a1,…,ak
3. Apply condition C2 to each group (may have aggregates)
4. Compute aggregates in S and return the result
SELECT S
FROM R1,…,Rn
WHERE C1
GROUP BY a1,…,ak
HAVING C2
Advanced SQLizing
1. Getting around INTERSECT and EXCEPT
2. Quantifiers
3. Aggregation v.s. subqueries
1. INTERSECT and EXCEPT:
(SELECT R.A, R.B
FROM R)
INTERSECT
(SELECT S.A, S.B
FROM S)
SELECT R.A, R.B
FROM R
WHERE
EXISTS(SELECT *
FROM S
WHERE R.A=S.A and R.B=S.B)
(SELECT R.A, R.B
FROM R)
EXCEPT
(SELECT S.A, S.B
FROM S)
SELECT R.A, R.B
FROM R
WHERE
NOT EXISTS(SELECT *
FROM S
WHERE R.A=S.A and R.B=S.B)
If R, S have no
duplicates, then can
write without
subqueries
(HOW ?)
INTERSECT and EXCEPT: not in SQL Server
2. Quantifiers
Product ( pname, price, company)
Company( cname, city)
Find all companies that make some products with price < 100
SELECT DISTINCT Company.cname
FROM Company, Product
WHERE Company.cname = Product.company and Product.price < 100
Existential: easy ! 
2. Quantifiers
Product ( pname, price, company)
Company( cname, city)
Find all companies s.t. all of their products have price < 100
Universal: hard ! 
Find all companies that make only products with price < 100
same as:
2. Quantifiers
2. Find all companies s.t. all their products have price < 100
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 Produc.price >= 100
SELECT DISTINCT Company.cname
FROM Company
WHERE Company.cname NOT IN (SELECT Product.company
FROM Product
WHERE Produc.price >= 100
3. Group-by v.s. Nested Query
• Find authors who wrote  10 documents:
• Attempt 1: with nested queries
SELECT DISTINCT Author.name
FROM Author
WHERE count(SELECT Wrote.url
FROM Wrote
WHERE Author.login=Wrote.login)
> 10
This is
SQL by
a novice
Author(login,name)
Wrote(login,url)
3. Group-by v.s. Nested Query
• Find all authors who wrote at least 10
documents:
• Attempt 2: SQL style (with GROUP BY)
SELECT Author.name
FROM Author, Wrote
WHERE Author.login=Wrote.login
GROUP BY Author.name
HAVING count(wrote.url) > 10
This is
SQL by
an expert
No need for DISTINCT: automatically from GROUP BY
3. Group-by v.s. Nested Query
Find authors with vocabulary  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
Author(login,name)
Wrote(login,url)
Mentions(url,word)
Two Examples
Store(sid, sname)
Product(pid, pname, price, sid)
Find all stores that sell only products with price > 100
same as:
Find all stores s.t. all their products have price > 100)
SELECT Store.name
FROM Store, Product
WHERE Store.sid = Product.sid
GROUP BY Store.sid, Store.name
HAVING 100 < min(Product.price)
SELECT Store.name
FROM Store
WHERE Store.sid NOT IN
(SELECT Product.sid
FROM Product
WHERE Product.price <= 100)
SELECT Store.name
FROM Store
WHERE
100 < ALL (SELECT Product.price
FROM product
WHERE Store.sid = Product.sid)
Almost equivalent…
Why both ?
Two Examples
Store(sid, sname)
Product(pid, pname, price, sid)
For each store,
find its most expensive product
Two Examples
SELECT Store.sname, max(Product.price)
FROM Store, Product
WHERE Store.sid = Product.sid
GROUP BY Store.sid, Store.sname
SELECT Store.sname, x.pname
FROM Store, Product x
WHERE Store.sid = x.sid and
x.price >=
ALL (SELECT y.price
FROM Product y
WHERE Store.sid = y.sid)
This is easy but doesn’t do what we want:
Better:
But may
return
multiple
product names
per store
Two Examples
SELECT Store.sname, max(x.pname)
FROM Store, Product x
WHERE Store.sid = x.sid and
x.price >=
ALL (SELECT y.price
FROM Product y
WHERE Store.sid = y.sid)
GROUP BY Store.sname
Finally, choose some pid arbitrarily, if there are many
with highest price:
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 can be null
(nullable attribute) or not
• How does SQL cope with tables that have NULLs ?
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
Null Values
• C1 AND C2 = min(C1, C2)
• C1 OR C2 = max(C1, C2)
• NOT C1 = 1 – C1
Rule in SQL: include only tuples that yield TRUE
SELECT *
FROM Person
WHERE (age < 25) AND
(height > 6 OR weight > 190)
E.g.
age=20
heigth=NULL
weight=200
Null Values
Unexpected behavior:
Some Persons are not included !
SELECT *
FROM Person
WHERE age < 25 OR age >= 25
Null Values
Can test for NULL explicitly:
– x IS NULL
– x IS NOT NULL
Now it includes all Persons
SELECT *
FROM Person
WHERE age < 25 OR age >= 25 OR age IS NULL
Outerjoins
Explicit joins in SQL = “inner joins”:
Product(name, category)
Purchase(prodName, store)
SELECT Product.name, Purchase.store
FROM Product JOIN Purchase ON
Product.name = Purchase.prodName
SELECT Product.name, Purchase.store
FROM Product, Purchase
WHERE Product.name = Purchase.prodName
Same as:
But Products that never sold will be lost !
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
Name Category
Gizmo gadget
Camera Photo
OneClick Photo
ProdName Store
Gizmo Wiz
Camera Ritz
Camera Wiz
Name Store
Gizmo Wiz
Camera Ritz
Camera Wiz
OneClick NULL
Product Purchase
Application
Compute, for each product, the total number of sales in ‘September’
Product(name, category)
Purchase(prodName, month, store)
SELECT Product.name, count(*)
FROM Product, Purchase
WHERE Product.name = Purchase.prodName
and Purchase.month = ‘September’
GROUP BY Product.name
What’s wrong ?
Application
Compute, for each product, the total number of sales in ‘September’
Product(name, category)
Purchase(prodName, month, store)
SELECT Product.name, count(*)
FROM Product LEFT OUTER JOIN Purchase ON
Product.name = Purchase.prodName
and Purchase.month = ‘September’
GROUP BY Product.name
Now we also get the products who sold in 0 quantity
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
Modifying the Database
Three kinds of modifications
• Insertions
• Deletions
• Updates
Sometimes they are all called “updates”
Insertions
General form:
Missing attribute  NULL.
May drop attribute names if give them in order.
INSERT INTO R(A1,…., An) VALUES (v1,…., vn)
INSERT INTO Purchase(buyer, seller, product, store)
VALUES (‘Joe’, ‘Fred’, ‘wakeup-clock-espresso-machine’,
‘The Sharper Image’)
Example: Insert a new purchase to the database:
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
Insertion: an Example
prodName is foreign key in Product.name
Suppose database got corrupted and we need to fix it:
name listPrice category
gizmo 100 gadgets
prodName buyerName price
camera John 200
gizmo Smith 80
camera Smith 225
Task: insert in Product all prodNames from Purchase
Product
Product(name, listPrice, category)
Purchase(prodName, buyerName, price)
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 - -
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 -
camera ?? 225 ?? - Depends on the implementation
Deletions
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.
Example:
Updates
UPDATE PRODUCT
SET price = price/2
WHERE Product.name IN
(SELECT product
FROM Purchase
WHERE Date =‘Oct, 25, 1999’);
Example:

More Related Content

Similar to lecture-SQL_Working.ppt

Week 11 - 02 - Structured Query Language.ppt
Week 11 - 02 - Structured Query Language.pptWeek 11 - 02 - Structured Query Language.ppt
Week 11 - 02 - Structured Query Language.pptSajjadAbdullah4
 
The Complete Presentation on SQL Server
The  Complete Presentation on SQL ServerThe  Complete Presentation on SQL Server
The Complete Presentation on SQL Serverkrishna43511
 
lecture sql server database basic for beginners
lecture sql server database basic for beginnerslecture sql server database basic for beginners
lecture sql server database basic for beginners21awais
 
SQL Basics - Lecture.ppt
SQL Basics - Lecture.pptSQL Basics - Lecture.ppt
SQL Basics - Lecture.pptErick Araújo
 
SQL BASICS.pptx
SQL BASICS.pptxSQL BASICS.pptx
SQL BASICS.pptxJEEVA R
 
lecture2.ppt
lecture2.pptlecture2.ppt
lecture2.pptImXaib
 
Slides 2-basic sql
Slides 2-basic sqlSlides 2-basic sql
Slides 2-basic sqlAnuja Lad
 
FOUNDATION OF DATA SCIENCE SQL QUESTIONS
FOUNDATION OF DATA SCIENCE SQL QUESTIONSFOUNDATION OF DATA SCIENCE SQL QUESTIONS
FOUNDATION OF DATA SCIENCE SQL QUESTIONSHITIKAJAIN4
 
Database Management System - SQL beginner Training
Database Management System - SQL beginner Training Database Management System - SQL beginner Training
Database Management System - SQL beginner Training Moutasm Tamimi
 
Database Management System - SQL Advanced Training
Database Management System - SQL Advanced TrainingDatabase Management System - SQL Advanced Training
Database Management System - SQL Advanced TrainingMoutasm Tamimi
 
SQL structure query language full presentation
SQL structure query language full presentationSQL structure query language full presentation
SQL structure query language full presentationJKarthickMyilvahanan
 
lec02-data-models-sql-basics.pptx
lec02-data-models-sql-basics.pptxlec02-data-models-sql-basics.pptx
lec02-data-models-sql-basics.pptxcAnhTrn53
 
React Native Performance
React Native Performance React Native Performance
React Native Performance InnerFood
 
How to Handle NoSQL with a Relational Database
How to Handle NoSQL with a Relational DatabaseHow to Handle NoSQL with a Relational Database
How to Handle NoSQL with a Relational DatabaseDATAVERSITY
 

Similar to lecture-SQL_Working.ppt (20)

lecture-sql.ppt
lecture-sql.pptlecture-sql.ppt
lecture-sql.ppt
 
Week 11 - 02 - Structured Query Language.ppt
Week 11 - 02 - Structured Query Language.pptWeek 11 - 02 - Structured Query Language.ppt
Week 11 - 02 - Structured Query Language.ppt
 
The Complete Presentation on SQL Server
The  Complete Presentation on SQL ServerThe  Complete Presentation on SQL Server
The Complete Presentation on SQL Server
 
lecture sql server database basic for beginners
lecture sql server database basic for beginnerslecture sql server database basic for beginners
lecture sql server database basic for beginners
 
SQL Basics - Lecture.ppt
SQL Basics - Lecture.pptSQL Basics - Lecture.ppt
SQL Basics - Lecture.ppt
 
SQL BASICS.pptx
SQL BASICS.pptxSQL BASICS.pptx
SQL BASICS.pptx
 
SQL Basic Queries
SQL Basic Queries SQL Basic Queries
SQL Basic Queries
 
Sql introduction
Sql introductionSql introduction
Sql introduction
 
lecture2.ppt
lecture2.pptlecture2.ppt
lecture2.ppt
 
lecture2.ppt
lecture2.pptlecture2.ppt
lecture2.ppt
 
Slides 2-basic sql
Slides 2-basic sqlSlides 2-basic sql
Slides 2-basic sql
 
FOUNDATION OF DATA SCIENCE SQL QUESTIONS
FOUNDATION OF DATA SCIENCE SQL QUESTIONSFOUNDATION OF DATA SCIENCE SQL QUESTIONS
FOUNDATION OF DATA SCIENCE SQL QUESTIONS
 
Sql for biggner
Sql for biggnerSql for biggner
Sql for biggner
 
Database Management System - SQL beginner Training
Database Management System - SQL beginner Training Database Management System - SQL beginner Training
Database Management System - SQL beginner Training
 
Database Management System - SQL Advanced Training
Database Management System - SQL Advanced TrainingDatabase Management System - SQL Advanced Training
Database Management System - SQL Advanced Training
 
SQL structure query language full presentation
SQL structure query language full presentationSQL structure query language full presentation
SQL structure query language full presentation
 
Sql server building a database ppt 12
Sql server building a database ppt 12Sql server building a database ppt 12
Sql server building a database ppt 12
 
lec02-data-models-sql-basics.pptx
lec02-data-models-sql-basics.pptxlec02-data-models-sql-basics.pptx
lec02-data-models-sql-basics.pptx
 
React Native Performance
React Native Performance React Native Performance
React Native Performance
 
How to Handle NoSQL with a Relational Database
How to Handle NoSQL with a Relational DatabaseHow to Handle NoSQL with a Relational Database
How to Handle NoSQL with a Relational Database
 

Recently uploaded

RSA Conference Exhibitor List 2024 - Exhibitors Data
RSA Conference Exhibitor List 2024 - Exhibitors DataRSA Conference Exhibitor List 2024 - Exhibitors Data
RSA Conference Exhibitor List 2024 - Exhibitors DataExhibitors Data
 
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Dave Litwiller
 
Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Neil Kimberley
 
Dr. Admir Softic_ presentation_Green Club_ENG.pdf
Dr. Admir Softic_ presentation_Green Club_ENG.pdfDr. Admir Softic_ presentation_Green Club_ENG.pdf
Dr. Admir Softic_ presentation_Green Club_ENG.pdfAdmir Softic
 
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLMONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLSeo
 
Boost the utilization of your HCL environment by reevaluating use cases and f...
Boost the utilization of your HCL environment by reevaluating use cases and f...Boost the utilization of your HCL environment by reevaluating use cases and f...
Boost the utilization of your HCL environment by reevaluating use cases and f...Roland Driesen
 
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779Delhi Call girls
 
Pharma Works Profile of Karan Communications
Pharma Works Profile of Karan CommunicationsPharma Works Profile of Karan Communications
Pharma Works Profile of Karan Communicationskarancommunications
 
M.C Lodges -- Guest House in Jhang.
M.C Lodges --  Guest House in Jhang.M.C Lodges --  Guest House in Jhang.
M.C Lodges -- Guest House in Jhang.Aaiza Hassan
 
Ensure the security of your HCL environment by applying the Zero Trust princi...
Ensure the security of your HCL environment by applying the Zero Trust princi...Ensure the security of your HCL environment by applying the Zero Trust princi...
Ensure the security of your HCL environment by applying the Zero Trust princi...Roland Driesen
 
Regression analysis: Simple Linear Regression Multiple Linear Regression
Regression analysis:  Simple Linear Regression Multiple Linear RegressionRegression analysis:  Simple Linear Regression Multiple Linear Regression
Regression analysis: Simple Linear Regression Multiple Linear RegressionRavindra Nath Shukla
 
Call Girls in Gomti Nagar - 7388211116 - With room Service
Call Girls in Gomti Nagar - 7388211116  - With room ServiceCall Girls in Gomti Nagar - 7388211116  - With room Service
Call Girls in Gomti Nagar - 7388211116 - With room Servicediscovermytutordmt
 
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Dipal Arora
 
Call Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine ServiceCall Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine Serviceritikaroy0888
 
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...Lviv Startup Club
 
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxB.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxpriyanshujha201
 
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...lizamodels9
 
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangaloreamitlee9823
 

Recently uploaded (20)

RSA Conference Exhibitor List 2024 - Exhibitors Data
RSA Conference Exhibitor List 2024 - Exhibitors DataRSA Conference Exhibitor List 2024 - Exhibitors Data
RSA Conference Exhibitor List 2024 - Exhibitors Data
 
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
 
Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023
 
Dr. Admir Softic_ presentation_Green Club_ENG.pdf
Dr. Admir Softic_ presentation_Green Club_ENG.pdfDr. Admir Softic_ presentation_Green Club_ENG.pdf
Dr. Admir Softic_ presentation_Green Club_ENG.pdf
 
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLMONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
 
Boost the utilization of your HCL environment by reevaluating use cases and f...
Boost the utilization of your HCL environment by reevaluating use cases and f...Boost the utilization of your HCL environment by reevaluating use cases and f...
Boost the utilization of your HCL environment by reevaluating use cases and f...
 
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
 
VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
 
Pharma Works Profile of Karan Communications
Pharma Works Profile of Karan CommunicationsPharma Works Profile of Karan Communications
Pharma Works Profile of Karan Communications
 
M.C Lodges -- Guest House in Jhang.
M.C Lodges --  Guest House in Jhang.M.C Lodges --  Guest House in Jhang.
M.C Lodges -- Guest House in Jhang.
 
unwanted pregnancy Kit [+918133066128] Abortion Pills IN Dubai UAE Abudhabi
unwanted pregnancy Kit [+918133066128] Abortion Pills IN Dubai UAE Abudhabiunwanted pregnancy Kit [+918133066128] Abortion Pills IN Dubai UAE Abudhabi
unwanted pregnancy Kit [+918133066128] Abortion Pills IN Dubai UAE Abudhabi
 
Ensure the security of your HCL environment by applying the Zero Trust princi...
Ensure the security of your HCL environment by applying the Zero Trust princi...Ensure the security of your HCL environment by applying the Zero Trust princi...
Ensure the security of your HCL environment by applying the Zero Trust princi...
 
Regression analysis: Simple Linear Regression Multiple Linear Regression
Regression analysis:  Simple Linear Regression Multiple Linear RegressionRegression analysis:  Simple Linear Regression Multiple Linear Regression
Regression analysis: Simple Linear Regression Multiple Linear Regression
 
Call Girls in Gomti Nagar - 7388211116 - With room Service
Call Girls in Gomti Nagar - 7388211116  - With room ServiceCall Girls in Gomti Nagar - 7388211116  - With room Service
Call Girls in Gomti Nagar - 7388211116 - With room Service
 
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
 
Call Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine ServiceCall Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine Service
 
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
 
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxB.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
 
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
 
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 

lecture-SQL_Working.ppt

  • 1. SQL • SQL is a database computer language designed for the retrieval and management of data in a relational database. SQL stands for Structured Query Language. • SQL is used to communicate with a database. • According to ANSI (American National Standards Institute), it is the standard language for relational database management systems. SQL statements are used to perform tasks such as update data on a database, or retrieve data from a database. Some common relational database management systems that use SQL are: Oracle, Sybase, Microsoft SQL Server, Access, Ingres, etc.
  • 2. SQL Conti… • As the name suggests, it is used when we have structured data (in the form of tables). All databases that are not relational (or do not use fixed structure tables to store data) and therefore do not use SQL, are called NoSQL databases. Examples of NoSQL are MongoDB, DynamoDB, Cassandra, Hadoop etc
  • 3. SQL Conti… • SQL is case insensitive. But it is a recommended practice to use keywords (like SELECT, UPDATE, CREATE, etc) in capital letters and use user defined things (liked table name, column name, etc) in small letters. • We can write comments in SQL using “–” (double hyphen) at the beginning of any line.
  • 4. SQL Conti… • SQL is the programming language for relational databases (explained below) like MySQL, Oracle, Sybase, SQL Server, Postgre, etc. Other non- relational databases (also called NoSQL) databases like MongoDB, DynamoDB, etc do not use SQL • Although there is an ISO standard for SQL, most of the implementations slightly vary in syntax. So we may encounter queries that work in SQL Server but do not work in MySQL, Oracle etc.
  • 9. SQL History • IBM Sequel language developed as part of System R project at the IBM San Jose Research Laboratory • Renamed Structured Query Language (SQL) • ANSI and ISO standard SQL: – SQL-86 – SQL-89 – SQL-92 – SQL:1999 – SQL:2003
  • 10. Tables in SQL PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Product Attribute names Table name Tuples or rows
  • 11. Tables Explained • The schema of a table is the table name and its attributes: Product(PName, Price, Category, Manfacturer) • A key is an attribute whose values are unique; we underline a key Product(PName, Price, Category, Manfacturer)
  • 12. Tables Explained • SQL> create table students • 2 ( • 3 roll int not null, • 4 name varchar2(30) not null, • 5 address varchar2(50) not null, • 6 contact int not null • 7 ) • 8 / • Table created. • SQL>
  • 13. Tables Explained • SQL> insert into students • 2 values(120, 'Sachin', 'Mumbai',2465218); • 1 row created.
  • 14. Tables Explained • SQL> insert into students • 2 values(234, 'Rahul', 'Bengluru',222222); • 1 row created. • SQL> insert into students • 2 values(111, 'Saurav Ganguly', 'Kolkata',3333); • 1 row created.
  • 15. Tables Explained • SQL> insert into students • 2 values(345, 'Mayank Agrawal', 'Mathura',7777777); • 1 row created. • SQL> insert into students • 2 values(120, 'Deepak Chahar', 'Agra',99999); • 1 row created.
  • 16. Set Linesize • SQL> show linesize • linesize 80 • SQL> set linesize 150 • SQL> show linesize • linesize 150
  • 17. Set Pagesize • SQL> show pagesiz • pagesize 14 • SQL> set pagesize 50 • SQL> show pagesize • pagesize 50
  • 18. Set Pagesize • SQL> set linesize 70 • SQL> select * from students; • SQL> select * from students • 2 where roll=120;
  • 19. Tables Explained • A table = a set of tuples
  • 20. SQL Query SELECT <attributes> FROM <one or more relations> WHERE <conditions>
  • 21. Simple SQL Query 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’ Product PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks “selection”
  • 22. Simple SQL Query 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 Product PName Price Manufacturer SingleTouch $149.99 Canon MultiTouch $203.99 Hitachi “selection” and “projection”
  • 23. Notation Product(PName, Price, Category, Manfacturer) Answer(PName, Price, Manfacturer) Input Schema Output Schema SELECT PName, Price, Manufacturer FROM Product WHERE Price > 100
  • 24. Details • Case insensitive: – Same: SELECT Select select – Same: Product product – Different: ‘Seattle’ ‘seattle’ • Constants: – ‘abc’ - yes – “abc” - no
  • 25. The LIKE operator • s LIKE p: pattern matching on strings • p may contain two special symbols: – % = any sequence of characters – _ = any single character SELECT * FROM Products WHERE PName LIKE ‘%gizmo%’
  • 26. Eliminating Duplicates SELECT DISTINCT category FROM Product Compare to: SELECT category FROM Product Category Gadgets Gadgets Photography Household Category Gadgets Photography Household
  • 27. Ordering the Results SELECT pname, price, manufacturer FROM Product WHERE category=‘gizmo’AND price > 50 ORDER BY price, pname Ties are broken by the second attribute on the ORDER BY list, etc. Ordering is ascending, unless you specify the DESC keyword.
  • 28. 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 ? SELECT DISTINCT category FROM Product ORDER BY category SELECT DISTINCT category FROM Product ORDER BY PName ? ?
  • 29. Keys and Foreign Keys PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Product Company CName StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 Japan Key Foreign key
  • 30. Joins Product (pname, price, category, manufacturer) Company (cname, stockPrice, country) Find all products under $200 manufactured in Japan; return their names and prices. SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200 Join between Product and Company
  • 31. Joins PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Product Company Cname StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 Japan PName Price SingleTouch $149.99 SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200
  • 32. More Joins Product (pname, price, category, manufacturer) Company (cname, stockPrice, country) Find all Chinese companies that manufacture products both in the ‘electronic’ and ‘toy’ categories SELECT cname FROM WHERE
  • 33. A Subtlety about 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’ Unexpected duplicates
  • 34. A Subtlety about Joins Name Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Product Company Cname StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 Japan Country ?? ?? What is the problem ? What’s the solution ? SELECT Country FROM Product, Company WHERE Manufacturer=CName AND Category=‘Gadgets’
  • 35. Tuple Variables SELECT DISTINCT pname, address FROM Person, Company WHERE worksfor = cname Which address ? Person(pname, address, worksfor) Company(cname, address) SELECT DISTINCT Person.pname, Company.address FROM Person, Company WHERE Person.worksfor = Company.cname SELECT DISTINCT x.pname, y.address FROM Person AS x, Company AS y WHERE x.worksfor = y.cname
  • 36. Meaning (Semantics) of SQL Queries SELECT a1, a2, …, ak FROM R1 AS x1, R2 AS x2, …, Rn AS xn WHERE Conditions Answer = {} for x1 in R1 do for x2 in R2 do ….. for xn in Rn do if Conditions then Answer = Answer  {(a1,…,ak)} return Answer
  • 37. SELECT DISTINCT R.A FROM R, S, T WHERE R.A=S.A OR R.A=T.A An Unintuitive Query Computes R  (S  T) But what if S = f ? What does it compute ?
  • 38. Subqueries Returning Relations SELECT Company.city FROM Company WHERE Company.name IN (SELECT Product.maker FROM Purchase , Product WHERE Product.pname=Purchase.product AND Purchase .buyer = ‘Joe Blow‘); Return cities where one can find companies that manufacture products bought by Joe Blow Company(name, city) Product(pname, maker) Purchase(id, product, buyer)
  • 39. Subqueries Returning Relations SELECT Company.city FROM Company, Product, Purchase WHERE Company.name= Product.maker AND Product.pname = Purchase.product AND Purchase.buyer = ‘Joe Blow’ Is it equivalent to this ? Beware of duplicates !
  • 40. Removing Duplicates Now they are equivalent SELECT DISTINCT Company.city FROM Company WHERE Company.name IN (SELECT Product.maker FROM Purchase , Product WHERE Product.pname=Purchase.product AND Purchase .buyer = ‘Joe Blow‘); SELECT DISTINCT Company.city FROM Company, Product, Purchase WHERE Company.name= Product.maker AND Product.pname = Purchase.product AND Purchase.buyer = ‘Joe Blow’
  • 41. Subqueries Returning Relations SELECT name FROM Product WHERE price > ALL (SELECT price FROM Purchase WHERE maker=‘Gizmo-Works’) Product ( pname, price, category, maker) Find products that are more expensive than all those produced By “Gizmo-Works” You can also use: s > ALL R s > ANY R EXISTS R
  • 42. Question for Database Fans and their Friends • Can we express this query as a single SELECT-FROM-WHERE query, without subqueries ?
  • 43. Question for Database Fans and their Friends • Answer: all SFW queries are monotone (figure out what this means). A query with ALL is not monotone
  • 44. Correlated Queries SELECT DISTINCT title FROM Movie AS x WHERE year <> ANY (SELECT year FROM Movie WHERE title = x.title); Movie (title, year, director, length) Find movies whose title appears more than once. Note (1) scope of variables (2) this can still be expressed as single SFW correlation
  • 45. 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 Very powerful ! Also much harder to optimize. 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);
  • 46. Aggregation SELECT count(*) FROM Product WHERE year > 1995 Except count, all aggregations apply to a single attribute SELECT avg(price) FROM Product WHERE maker=“Toyota” SQL supports several aggregation operations: sum, count, min, max, avg
  • 47. COUNT applies to duplicates, unless otherwise stated: SELECT Count(category) FROM Product WHERE year > 1995 same as Count(*) We probably want: SELECT Count(DISTINCT category) FROM Product WHERE year > 1995 Aggregation: Count
  • 48. Purchase(product, date, price, quantity) More Examples SELECT Sum(price * quantity) FROM Purchase SELECT Sum(price * quantity) FROM Purchase WHERE product = ‘bagel’ What do they mean ?
  • 49. Simple Aggregations Purchase Product Date Price Quantity Bagel 10/21 1 20 Banana 10/3 0.5 10 Banana 10/10 1 10 Bagel 10/25 1.50 20 SELECT Sum(price * quantity) FROM Purchase WHERE product = ‘bagel’ 50 (= 20+30)
  • 50. Grouping and Aggregation Purchase(product, date, price, quantity) SELECT product, Sum(price*quantity) AS TotalSales FROM Purchase WHERE date > ‘10/1/2005’ GROUP BY product Let’s see what this means… Find total sales after 10/1/2005 per product.
  • 51. Grouping and Aggregation 1. Compute the FROM and WHERE clauses. 2. Group by the attributes in the GROUPBY 3. Compute the SELECT clause: grouped attributes and aggregates.
  • 52. 1&2. FROM-WHERE-GROUPBY Product Date Price Quantity Bagel 10/21 1 20 Bagel 10/25 1.50 20 Banana 10/3 0.5 10 Banana 10/10 1 10
  • 53. 3. SELECT SELECT product, Sum(price*quantity) AS TotalSales FROM Purchase WHERE date > ‘10/1/2005’ GROUP BY product Product Date Price Quantity Bagel 10/21 1 20 Bagel 10/25 1.50 20 Banana 10/3 0.5 10 Banana 10/10 1 10 Product TotalSales Bagel 50 Banana 15
  • 54. GROUP BY v.s. Nested Quereis SELECT product, Sum(price*quantity) AS TotalSales FROM Purchase WHERE date > ‘10/1/2005’ GROUP BY product SELECT DISTINCT x.product, (SELECT Sum(y.price*y.quantity) FROM Purchase y WHERE x.product = y.product AND y.date > ‘10/1/2005’) AS TotalSales FROM Purchase x WHERE x.date > ‘10/1/2005’
  • 55. Another Example SELECT product, sum(price * quantity) AS SumSales max(quantity) AS MaxQuantity FROM Purchase GROUP BY product What does it mean ?
  • 56. HAVING Clause SELECT product, Sum(price * quantity) FROM Purchase WHERE date > ‘10/1/2005’ GROUP BY product HAVING Sum(quantity) > 30 Same query, except that we consider only products that had at least 100 buyers. HAVING clause contains conditions on aggregates.
  • 57. General form of Grouping and Aggregation SELECT S FROM R1,…,Rn WHERE C1 GROUP BY a1,…,ak HAVING C2 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 Why ?
  • 58. General form of Grouping and Aggregation Evaluation steps: 1. Evaluate FROM-WHERE, apply condition C1 2. Group by the attributes a1,…,ak 3. Apply condition C2 to each group (may have aggregates) 4. Compute aggregates in S and return the result SELECT S FROM R1,…,Rn WHERE C1 GROUP BY a1,…,ak HAVING C2
  • 59. Advanced SQLizing 1. Getting around INTERSECT and EXCEPT 2. Quantifiers 3. Aggregation v.s. subqueries
  • 60. 1. INTERSECT and EXCEPT: (SELECT R.A, R.B FROM R) INTERSECT (SELECT S.A, S.B FROM S) SELECT R.A, R.B FROM R WHERE EXISTS(SELECT * FROM S WHERE R.A=S.A and R.B=S.B) (SELECT R.A, R.B FROM R) EXCEPT (SELECT S.A, S.B FROM S) SELECT R.A, R.B FROM R WHERE NOT EXISTS(SELECT * FROM S WHERE R.A=S.A and R.B=S.B) If R, S have no duplicates, then can write without subqueries (HOW ?) INTERSECT and EXCEPT: not in SQL Server
  • 61. 2. Quantifiers Product ( pname, price, company) Company( cname, city) Find all companies that make some products with price < 100 SELECT DISTINCT Company.cname FROM Company, Product WHERE Company.cname = Product.company and Product.price < 100 Existential: easy ! 
  • 62. 2. Quantifiers Product ( pname, price, company) Company( cname, city) Find all companies s.t. all of their products have price < 100 Universal: hard !  Find all companies that make only products with price < 100 same as:
  • 63. 2. Quantifiers 2. Find all companies s.t. all their products have price < 100 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 Produc.price >= 100 SELECT DISTINCT Company.cname FROM Company WHERE Company.cname NOT IN (SELECT Product.company FROM Product WHERE Produc.price >= 100
  • 64. 3. Group-by v.s. Nested Query • Find authors who wrote  10 documents: • Attempt 1: with nested queries SELECT DISTINCT Author.name FROM Author WHERE count(SELECT Wrote.url FROM Wrote WHERE Author.login=Wrote.login) > 10 This is SQL by a novice Author(login,name) Wrote(login,url)
  • 65. 3. Group-by v.s. Nested Query • Find all authors who wrote at least 10 documents: • Attempt 2: SQL style (with GROUP BY) SELECT Author.name FROM Author, Wrote WHERE Author.login=Wrote.login GROUP BY Author.name HAVING count(wrote.url) > 10 This is SQL by an expert No need for DISTINCT: automatically from GROUP BY
  • 66. 3. Group-by v.s. Nested Query Find authors with vocabulary  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 Author(login,name) Wrote(login,url) Mentions(url,word)
  • 67. Two Examples Store(sid, sname) Product(pid, pname, price, sid) Find all stores that sell only products with price > 100 same as: Find all stores s.t. all their products have price > 100)
  • 68. SELECT Store.name FROM Store, Product WHERE Store.sid = Product.sid GROUP BY Store.sid, Store.name HAVING 100 < min(Product.price) SELECT Store.name FROM Store WHERE Store.sid NOT IN (SELECT Product.sid FROM Product WHERE Product.price <= 100) SELECT Store.name FROM Store WHERE 100 < ALL (SELECT Product.price FROM product WHERE Store.sid = Product.sid) Almost equivalent… Why both ?
  • 69. Two Examples Store(sid, sname) Product(pid, pname, price, sid) For each store, find its most expensive product
  • 70. Two Examples SELECT Store.sname, max(Product.price) FROM Store, Product WHERE Store.sid = Product.sid GROUP BY Store.sid, Store.sname SELECT Store.sname, x.pname FROM Store, Product x WHERE Store.sid = x.sid and x.price >= ALL (SELECT y.price FROM Product y WHERE Store.sid = y.sid) This is easy but doesn’t do what we want: Better: But may return multiple product names per store
  • 71. Two Examples SELECT Store.sname, max(x.pname) FROM Store, Product x WHERE Store.sid = x.sid and x.price >= ALL (SELECT y.price FROM Product y WHERE Store.sid = y.sid) GROUP BY Store.sname Finally, choose some pid arbitrarily, if there are many with highest price:
  • 72. 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 can be null (nullable attribute) or not • How does SQL cope with tables that have NULLs ?
  • 73. 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
  • 74. Null Values • C1 AND C2 = min(C1, C2) • C1 OR C2 = max(C1, C2) • NOT C1 = 1 – C1 Rule in SQL: include only tuples that yield TRUE SELECT * FROM Person WHERE (age < 25) AND (height > 6 OR weight > 190) E.g. age=20 heigth=NULL weight=200
  • 75. Null Values Unexpected behavior: Some Persons are not included ! SELECT * FROM Person WHERE age < 25 OR age >= 25
  • 76. Null Values Can test for NULL explicitly: – x IS NULL – x IS NOT NULL Now it includes all Persons SELECT * FROM Person WHERE age < 25 OR age >= 25 OR age IS NULL
  • 77. Outerjoins Explicit joins in SQL = “inner joins”: Product(name, category) Purchase(prodName, store) SELECT Product.name, Purchase.store FROM Product JOIN Purchase ON Product.name = Purchase.prodName SELECT Product.name, Purchase.store FROM Product, Purchase WHERE Product.name = Purchase.prodName Same as: But Products that never sold will be lost !
  • 78. 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
  • 79. Name Category Gizmo gadget Camera Photo OneClick Photo ProdName Store Gizmo Wiz Camera Ritz Camera Wiz Name Store Gizmo Wiz Camera Ritz Camera Wiz OneClick NULL Product Purchase
  • 80. Application Compute, for each product, the total number of sales in ‘September’ Product(name, category) Purchase(prodName, month, store) SELECT Product.name, count(*) FROM Product, Purchase WHERE Product.name = Purchase.prodName and Purchase.month = ‘September’ GROUP BY Product.name What’s wrong ?
  • 81. Application Compute, for each product, the total number of sales in ‘September’ Product(name, category) Purchase(prodName, month, store) SELECT Product.name, count(*) FROM Product LEFT OUTER JOIN Purchase ON Product.name = Purchase.prodName and Purchase.month = ‘September’ GROUP BY Product.name Now we also get the products who sold in 0 quantity
  • 82. 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
  • 83. Modifying the Database Three kinds of modifications • Insertions • Deletions • Updates Sometimes they are all called “updates”
  • 84. Insertions General form: Missing attribute  NULL. May drop attribute names if give them in order. INSERT INTO R(A1,…., An) VALUES (v1,…., vn) INSERT INTO Purchase(buyer, seller, product, store) VALUES (‘Joe’, ‘Fred’, ‘wakeup-clock-espresso-machine’, ‘The Sharper Image’) Example: Insert a new purchase to the database:
  • 85. 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
  • 86. Insertion: an Example prodName is foreign key in Product.name Suppose database got corrupted and we need to fix it: name listPrice category gizmo 100 gadgets prodName buyerName price camera John 200 gizmo Smith 80 camera Smith 225 Task: insert in Product all prodNames from Purchase Product Product(name, listPrice, category) Purchase(prodName, buyerName, price) Purchase
  • 87. 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 - -
  • 88. 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 - camera ?? 225 ?? - Depends on the implementation
  • 89. Deletions 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. Example:
  • 90. Updates UPDATE PRODUCT SET price = price/2 WHERE Product.name IN (SELECT product FROM Purchase WHERE Date =‘Oct, 25, 1999’); Example: