SlideShare ist ein Scribd-Unternehmen logo
1 von 132
Structure Query Language (SQL)
Rithik Raj Vaishya
Data Scientist | Corporate Trainer
Dec-22 SQL 1
SQL Introduction
2
Standard language for querying and manipulating data
Structured Query Language
Many standards out there:
• ANSI SQL, SQL92 (a.k.a. SQL2), SQL99 (a.k.a. SQL3), ….
• Vendors support various subsets: watch for fun discussions in class !
SQL
• Data Definition Language (DDL)
• Create/alter/delete tables and their attributes
• Following lectures...
• Data Manipulation Language (DML)
• Query one or more tables – discussed next !
• Insert/delete/modify tuples in tables
3
Tables in SQL
4
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)
Dec-22 SQL 5
Data Types in SQL
• Atomic types:
• Characters: CHAR(20), VARCHAR(50)
• Numbers: INT, BIGINT, SMALLINT, FLOAT
• Others: MONEY, DATETIME, …
• Every attribute must have an atomic type
• Hence tables are flat
• Why ?
Dec-22 SQL 6
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().
Dec-22 SQL 7
SQL Query
Dec-22 SQL 8
Basic form: (plus many many more bells and whistles)
SELECT <attributes>
FROM <one or more relations>
WHERE <conditions>
Simple SQL Query
Dec-22 SQL 9
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
Dec-22 SQL 10
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
Dec-22 SQL 11
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
Dec-22 SQL 12
The LIKE operator
• s LIKE p: pattern matching on strings
• p may contain two special symbols:
• % = any sequence of characters
• _ = any single character
Dec-22 SQL 13
SELECT *
FROM Products
WHERE PName LIKE ‘%gizmo%’
Eliminating Duplicates
Dec-22 SQL 14
SELECT DISTINCT category
FROM Product
Compare to:
SELECT category
FROM Product
Category
Gadgets
Gadgets
Photography
Household
Category
Gadgets
Photography
Household
Ordering the Results
Dec-22 SQL 15
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
?
?
Dec-22 SQL 16
Keys and Foreign Keys
Dec-22 SQL 17
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
Dec-22 SQL 18
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
Dec-22 SQL 19
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
Dec-22 SQL 20
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
Dec-22 SQL 21
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
Dec-22 SQL 22
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
Dec-22 SQL 23
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
Dec-22 SQL 24
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
Dec-22 SQL 25
Computes R  (S  T) But what if S = f ?
What does it compute ?
Subqueries Returning Relations
Dec-22 SQL 26
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
Dec-22 SQL 27
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
Dec-22 SQL 28
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
Dec-22 SQL 29
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 ?
Dec-22 SQL 30
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
Dec-22 SQL 31
Correlated Queries
Dec-22 SQL 32
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.
Dec-22 SQL 33
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
Dec-22 SQL 34
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
Dec-22 SQL 35
Purchase(product, date, price, quantity)
More Examples
Dec-22 SQL 36
SELECT Sum(price * quantity)
FROM Purchase
SELECT Sum(price * quantity)
FROM Purchase
WHERE product = ‘bagel’
What do
they mean ?
Simple Aggregations
Dec-22 SQL 37
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
Dec-22 SQL 38
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
Dec-22 SQL 39
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
Dec-22 SQL 40
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
Dec-22 SQL 41
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
Dec-22 SQL 42
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
Dec-22 SQL 43
SELECT product,
sum(price * quantity) AS SumSales
max(quantity) AS MaxQuantity
FROM Purchase
GROUP BY product
What does
it mean ?
HAVING Clause
Dec-22 SQL 44
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
Dec-22 SQL 45
Why ?
General form of Grouping and Aggregation
Dec-22 SQL 46
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
Dec-22 SQL 47
1. INTERSECT and EXCEPT:
Dec-22 SQL 48
(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
Dec-22 SQL 49
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
Dec-22 SQL 50
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
Dec-22 SQL 51
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
Dec-22 SQL 52
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)
Dec-22 SQL 53
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
Dec-22 SQL 54
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
Dec-22 SQL 55
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 ?
Dec-22 SQL 56
Two Examples
Dec-22 SQL 57
Store(sid, sname)
Product(pid, pname, price, sid)
For each store,
find its most expensive product
Two Examples
Dec-22 SQL 58
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
Dec-22 SQL 59
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 ?
Dec-22 SQL 60
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
Dec-22 SQL 61
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
Dec-22 SQL 62
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 !
Dec-22 SQL 63
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
Dec-22 SQL 64
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)
Dec-22 SQL 65
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)
Dec-22 SQL 66
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
Dec-22 SQL 67
Application
Compute, for each product, the total number of sales in ‘September’
Product(name, category)
Purchase(prodName, month, store)
Dec-22 SQL 68
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)
Dec-22 SQL 69
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
Dec-22 SQL 70
Modifying the Database
Three kinds of modifications
• Insertions
• Deletions
• Updates
Sometimes they are all called “updates”
Dec-22 SQL 71
Insertions
Dec-22 SQL 72
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
Dec-22 SQL 73
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
Dec-22 SQL 74
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
Dec-22 SQL 75
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
Dec-22 SQL 76
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
Dec-22 SQL 77
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
Dec-22 SQL 78
UPDATE PRODUCT
SET price = price/2
WHERE Product.name IN
(SELECT product
FROM Purchase
WHERE Date =‘Oct, 25, 1999’);
Example:
Thank You !!
Dec-22 SQL 79
Introduction to Relational
Databases
Rithik Raj Vaishya
Data Scientist | Corporate Trainer
Introduction
• Database – collection of persistent data
• Database Management System (DBMS) – software system that
supports creation, population, and querying of a database
Relational Database
• Relational Database Management System (RDBMS)
• Consists of a number of tables and single schema (definition of tables and
attributes)
• Students (sid, name, login, age, gpa)
Students identifies the table
sid, name, login, age, gpa identify attributes
sid is primary key
An Example Table
• Students (sid: string, name: string, login: string, age: integer,
gpa: real)
sid name login age gpa
50000 Dave dave@cs 19 3.3
53666 Jones jones@cs 18 3.4
53688 Smith smith@ee 18 3.2
53650 Smith smith@math 19 3.8
53831 Madayan madayan@music 11 1.8
53832 Guldu guldu@music 12 2.0
Another example: Courses
• Courses (cid, instructor, quarter, dept)
cid instructor quarter dept
Carnatic101 Jane Fall 06 Music
Reggae203 Bob Summer 06 Music
Topology101 Mary Spring 06 Math
History105 Alice Fall 06 History
Keys
• Primary key – minimal subset of fields that is unique identifier for a
tuple
• sid is primary key for Students
• cid is primary key for Courses
• Foreign key –connections between tables
• Courses (cid, instructor, quarter, dept)
• Students (sid, name, login, age, gpa)
• How do we express which students take each course?
Many to many relationships
• In general, need a new table
Enrolled(cid, grade, studid)
Studid is foreign key that references sid in Student
table
cid grade studid
Carnatic101 C 53831
Reggae203 B 53832
Topology112 A 53650
History 105 B 53666
sid name login
50000 Dave dave@cs
53666 Jones jones@cs
53688 Smith smith@ee
53650 Smith smith@math
53831 Madayan madayan@music
53832 Guldu guldu@music
Enrolled
Student
Foreign
key
Relational Algebra
• Collection of operators for specifying queries
• Query describes step-by-step procedure for computing answer (i.e.,
operational)
• Each operator accepts one or two relations as input and returns a
relation as output
• Relational algebra expression composed of multiple operators
Basic operators
• Selection – return rows that meet some condition
• Projection – return column values
• Union
• Cross product
• Difference
• Other operators can be defined in terms of basic operators
Example Schema (simplified)
• Courses (cid, instructor, quarter, dept)
• Students (sid, name, gpa)
• Enrolled (cid, grade, studid)
Selection
Select students with gpa higher than 3.3 from S1:
σgpa>3.3(S1)
sid name gpa
50000 Dave 3.3
53666 Jones 3.4
53688 Smith 3.2
53650 Smith 3.8
53831 Madayan 1.8
53832 Guldu 2.0
S1
sid name gpa
53666 Jones 3.4
53650 Smith 3.8
Projection
Project name and gpa of all students in S1:
name, gpa(S1)
S1
Sid name gpa
50000 Dave 3.3
53666 Jones 3.4
53688 Smith 3.2
53650 Smith 3.8
53831 Madayan 1.8
53832 Guldu 2.0
name gpa
Dave 3.3
Jones 3.4
Smith 3.2
Smith 3.8
Madayan 1.8
Guldu 2.0
Combine Selection and Projection
• Project name and gpa of students in S1 with gpa
higher than 3.3:
name,gpa(σgpa>3.3(S1))
Sid name gpa
50000 Dave 3.3
53666 Jones 3.4
53688 Smith 3.2
53650 Smith 3.8
53831 Madayan 1.8
53832 Guldu 2.0
name gpa
Jones 3.4
Smith 3.8
Set Operations
• Union (R U S)
• All tuples in R or S (or both)
• R and S must have same number of fields
• Corresponding fields must have same domains
• Intersection (R ∩ S)
• All tuples in both R and S
• Set difference (R – S)
• Tuples in R and not S
Set Operations (continued)
• Cross product or Cartesian product (R x S)
• All fields in R followed by all fields in S
• One tuple (r,s) for each pair of tuples r  R, s  S
Example: Intersection
sid name gpa
50000 Dave 3.3
53666 Jones 3.4
53688 Smith 3.2
53650 Smith 3.8
53831 Madayan 1.8
53832 Guldu 2.0
sid name gpa
53666 Jones 3.4
53688 Smith 3.2
53700 Tom 3.5
53777 Jerry 2.8
53832 Guldu 2.0
S1 S2
S1  S2 =
sid name gpa
53666 Jones 3.4
53688 Smith 3.2
53832 Guldu 2.0
Joins
• Combine information from two or more tables
• Example: students enrolled in courses:
S1 S1.sid=E.studidE
Sid name gpa
50000 Dave 3.3
53666 Jones 3.4
53688 Smith 3.2
53650 Smith 3.8
53831 Madayan 1.8
53832 Guldu 2.0
cid grade studid
Carnatic101 C 53831
Reggae203 B 53832
Topology112 A 53650
History 105 B 53666
S1
E
Joins
sid name gpa cid grade studid
53666 Jones 3.4 History105 B 53666
53650 Smith 3.8 Topology112 A 53650
53831 Madayan 1.8 Carnatic101 C 53831
53832 Guldu 2.0 Reggae203 B 53832
Sid name gpa
50000 Dave 3.3
53666 Jones 3.4
53688 Smith 3.2
53650 Smith 3.8
53831 Madayan 1.8
53832 Guldu 2.0
cid grade studid
Carnatic101 C 53831
Reggae203 B 53832
Topology112 A 53650
History 105 B 53666
S1
E
Relational Algebra Summary
• Algebras are useful to manipulate data types (relations in
this case)
• Set-oriented
• Brings some clarity to what needs to be done
• Opportunities for optimization
• May have different expressions that do same thing
• We will see examples of algebras for other types of data
in this course
Intro to SQL
• CREATE TABLE
• Create a new table, e.g., students, courses, enrolled
• SELECT-FROM-WHERE
• List all CS courses
• INSERT
• Add a new student, course, or enroll a student in a course
Create Table
• CREATE TABLE Enrolled
(studid CHAR(20),
cid CHAR(20),
grade CHAR(20),
PRIMARY KEY (studid, cid),
FOREIGN KEY (studid) references Students)
Select-From-Where query
• “Find all students who are under 18”
SELECT *
FROM Students S
WHERE S.age < 18
Queries across multiple tables (joins)
• “Print the student name and course ID where the student received an
‘A’ in the course”
SELECT S.name, E.cid
FROM Students S, Enrolled E
WHERE S.sid = E.studid AND E.grade = ‘A’
Other SQL features
• MIN, MAX, AVG
• Find highest grade in fall database course
• COUNT, DISTINCT
• How many students enrolled in CS courses in the fall?
• ORDER BY, GROUP BY
• Rank students by their grade in fall database course
Views
• Virtual table defined on base tables defined by a query
• Single or multiple tables
• Security – “hide” certain attributes from users
• Show students in each course but hide their grades
• Ease of use – expression that is more intuitively
obvious to user
• Views can be materialized to improve query
performance
Views
• Suppose we often need names of students who got a
‘B’ in some course:
CREATE VIEW B_Students(name, sid, course)
AS SELECT S.sname, S.sid, E.cid
FROM Students S, Enrolled E
WHERE S.sid=E.studid and E.grade = ‘B’
name sid course
Jones 53666 History105
Guldu 53832 Reggae203
Indexes
• Idea: speed up access to desired data
• “Find all students with gpa > 3.3
• May need to scan entire table
• Index consists of a set of entries pointing to locations of each search
key
Types of Indexes
• Clustered vs. Unclustered
• Clustered- ordering of data records same as ordering of
data entries in the index
• Unclustered- data records in different order from index
• Primary vs. Secondary
• Primary – index on fields that include primary key
• Secondary – other indexes
Example: Clustered Index
• Sorted by sid
sid name gpa
50000 Dave 3.3
53650 Smith 3.8
53666 Jones 3.4
53688 Smith 3.2
53831 Madayan 1.8
53832 Guldu 2.0
50000
53600
53800
Example: Unclustered Index
• Sorted by sid
• Index on gpa
sid name gpa
50000 Dave 3.3
53650 Smith 3.8
53666 Jones 3.4
53688 Smith 3.2
53831 Madayan 1.8
53832 Guldu 2.0
1.8
2.0
3.2
3.3
3.4
3.8
Comments on Indexes
• Indexes can significantly speed up query execution
• But inserts more costly
• May have high storage overhead
• Need to choose attributes to index wisely!
• What queries are run most frequently?
• What queries could benefit most from an index?
• Preview of things to come: SDSS
Summary: Why are RDBMS useful?
• Data independence – provides abstract view of the
data, without details of storage
• Efficient data access – uses techniques to store and
retrieve data efficiently
• Reduced application development time – many
important functions already supported
• Centralized data administration
• Data Integrity and Security
• Concurrency control and recovery
So, why don’t scientists use them?
• “I tried to use databases in my project, but they were just too [slow |
hard-to-use | expensive | complex] . So I use files”.
• Gray and Szalay, Where Rubber Meets the Sky: Bridging the Gap Between
Databases and Science
Some other limitations of RDBMS
• Arrays
• Hierarchical data
Example: Taxonomy of Organisms
• Hierarchy of categories:
• Kingdom - phylum – class – order – family – genus - species
• How would you design a relational schema for this?
Animals
Chordates
Vertebrates
Arthropods
birds
insects spiders crustaceans
reptiles mammals
NoSQL
“T
owards the end of RDBMS?”
What is RDBMS
 RDBMS: the relational database
management system.
 Relation: a relation isa 2D table
which has the following features:
 Name
 Attributes
 Tuples
Name
2
Issueswith RDBMS- Scalability
 Issueswith scaling up when the dataset is
just too big e.g. Big Data.
 Not designed to be distributed.
 Looking at multi-node database solutions.
Known as ‘horizontal scaling’.
 Different approaches include:
 Master-slave
 Sharding
3
Scaling RDBMS
Master-Slave
 All writes are written to the master.
All reads are performed against
the replicated slave databases.
 Critical reads may be incorrect as
writes may not have been
propagated down.
 Large data sets can pose problems
as master needs to duplicate data
to slaves.
Sharding
 Scales well for both reads and
writes.
 Not transparent, application needs
to be partition-aware.
 Can nolonger have relationships or
joinsacrosspartitions.
 Loss of referential integrity across
shards.
4
What is NoSQL
 Standsfor Not Only SQL. T
ermwas redefined by Eric Evansafter Carlo
Strozzi.
 Class of non-relational data storage system
s.
 Do not require a fixed table schema nor do they use the concept of joins.
 Relaxation for oneor moreof the ACIDproperties (Atomicity,Consistency,
Isolation, Durability) using CAP theorem.
5
Need of NoSQL
 Explosion of social media sites (Facebook, Twitter, Google etc.) with large
data needs. (Sharding isa problem)
 Rise of cloud-based solutions such as Amazon S3 (simple storage solution).
 Just as moving to dynamically-typed languages (Ruby/Groovy), a shift to
dynamically-typed data with frequent schema changes.
 Expansion of Open-source community.
 NoSQL solution is more acceptable to a client now than a year ago.
6
NoSQL T
ypes
NoSQL database are classified into four types:
• Key Value pair based
• Column based
• Document based
• Graph based
7
Key Value P
air Based
• Designed for processing dictionary. Dictionaries contain a
collection of records having fields containing data.
• Records are stored and retrieved using a key that uniquely
identifies the record, and is used to quickly find the data
within the database.
Example: CouchDB, Oracle NoSQL Database, Riak etc.
We use it for storing session information, user profiles, preferences,
shopping cart data.
We would avoid it when we need to query data having relationships
between entities.
8
Column based
It store data as Column families containing rows that have
many columns associated with a row key. Each row can have
different columns.
Column families are groups of related data that is accessed
together.
Example: Cassandra, HBase, Hypertable, and Amazon
DynamoDB.
We use it for content management systems, blogging platforms, log aggregation.
We would avoid it for systems that are in early development, changing query patterns.
9
Document Based
Thedatabase stores and retrieves documents. It stores documents in
the value part of the key-value store.
Self- describing, hierarchical tree data structures consisting of maps,
collections, and scalar values.
Example: Lotus Notes, MongoDB, Couch DB,Orient DB,Raven DB.
We use it for content management systems, blogging platforms, web analytics, real-time analytics,
e- commerce applications.
We wouldavoid it for systemsthat need complextransactionsspanningmultiple operations or
queries against varying aggregate structures.
10
Graph Based
Store entities and relationships between these entities as nodes
and edges of a graph respectively. Entities have properties.
Traversing the relationships is very fast as relationship between
nodes is not calculated at query time but is actually persisted
as a relationship.
Example: Neo4J, Infinite Graph, OrientDB, FlockDB.
It is well suited for connected data, such as social networks,
spatial data, routing information for goods and supply.
11
CAP Theorem
 According to Eric Brewer a distributed system has3 properties :
 Consistency
 Availability
 Partitions
 We can have at most two of these three properties for any shared-data system
 Toscaleout,wehaveto partition. It leaves a choicebetween consistencyand
availability. ( In almost all cases, we would choose availability over consistency)
 Everyonewhobuilds big applications builds themonCAP:Google, Yahoo,
Facebook, Amazon, eBay, etc.
12
Advantages of NoSQL
 Cheap and easy to implement (open source)
 Data are replicated to multiple nodes (therefore identical and fault-
tolerant) and can be partitioned
 When data is written, the latest version is on at least one node and then
replicated to other nodes
 No single point of failure
 Easy to distribute
 Don't require a schema
13
What is not provided by NoSQL
 Joins
 Group by
 ACID transactions
 SQL
 Integration with applicationsthat are based on SQL
14
Where to use NoSQL
 NoSQL Data storage systems makes sense for applications that process very large
semi-structureddata –like LogAnalysis, Social Networking Feeds,Time-based
data.
 Toimprove programmer productivity by using a database that better matches an
application's needs.
 Toimprove data access performance via some combination of handling larger data
volumes, reducing latency, and improving throughput.
15
Conclusion
 All the choices provided by the rise of NoSQL databases does not mean the demiseof R
R
elational databases are a powerful tool.
 We are entering anera of Polyglot persistence,a technique that usesdifferent data stora
varying data storage needs.It canapply acrossan enterprise or within an individual app
16
R
eferences
1. “NoSQL Databases: An Overview”. Pramod Sadalage, thoughtworks.com(2014)
2. “Data managementincloud environments:NoSQLand NewSQLdata stores”.
Grolinger, K.; Higashino, W. A.; Tiwari, A.; Capretz, M. A. M. (2013). JoCCASA,
Springer.
3. “Making the Shift from Relational to NoSQL”. Couchbase.com(2014).
4. “NoSQL- Death to R
elational Databases”. Scofield, Ben (2010).
17
T
Th
ha
an
nk
k
Y
Y
o
o
u
u

Weitere ähnliche Inhalte

Ähnlich wie Data

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
 
lecture-SQL_Working.ppt
lecture-SQL_Working.pptlecture-SQL_Working.ppt
lecture-SQL_Working.pptLaviKushwaha
 
Slides 2-basic sql
Slides 2-basic sqlSlides 2-basic sql
Slides 2-basic sqlAnuja Lad
 
Database Management System - SQL Advanced Training
Database Management System - SQL Advanced TrainingDatabase Management System - SQL Advanced Training
Database Management System - SQL Advanced TrainingMoutasm Tamimi
 
lecture2.ppt
lecture2.pptlecture2.ppt
lecture2.pptImXaib
 
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
 
SQL structure query language full presentation
SQL structure query language full presentationSQL structure query language full presentation
SQL structure query language full presentationJKarthickMyilvahanan
 
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
 
[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05AnusAhmad
 

Ähnlich wie Data (20)

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-basic.ppt
sql-basic.pptsql-basic.ppt
sql-basic.ppt
 
SQL BASICS.pptx
SQL BASICS.pptxSQL BASICS.pptx
SQL BASICS.pptx
 
lecture-SQL_Working.ppt
lecture-SQL_Working.pptlecture-SQL_Working.ppt
lecture-SQL_Working.ppt
 
SQL Basic Queries
SQL Basic Queries SQL Basic Queries
SQL Basic Queries
 
Sql introduction
Sql introductionSql introduction
Sql introduction
 
Slides 2-basic sql
Slides 2-basic sqlSlides 2-basic sql
Slides 2-basic sql
 
Database Management System - SQL Advanced Training
Database Management System - SQL Advanced TrainingDatabase Management System - SQL Advanced Training
Database Management System - SQL Advanced Training
 
lecture2.ppt
lecture2.pptlecture2.ppt
lecture2.ppt
 
lecture2.ppt
lecture2.pptlecture2.ppt
lecture2.ppt
 
Database Management System - SQL beginner Training
Database Management System - SQL beginner Training Database Management System - SQL beginner Training
Database Management System - SQL beginner Training
 
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
 
SQL structure query language full presentation
SQL structure query language full presentationSQL structure query language full presentation
SQL structure query language full presentation
 
Sql for biggner
Sql for biggnerSql for biggner
Sql for biggner
 
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
 
Xamppinstallation edited
Xamppinstallation editedXamppinstallation edited
Xamppinstallation edited
 
SQL
SQL SQL
SQL
 
[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05
 

Mehr von RithikRaj25

Mehr von RithikRaj25 (17)

html1.ppt
html1.ppthtml1.ppt
html1.ppt
 
Data
DataData
Data
 
Introduction To Database.ppt
Introduction To Database.pptIntroduction To Database.ppt
Introduction To Database.ppt
 
Data.ppt
Data.pptData.ppt
Data.ppt
 
DataTypes.ppt
DataTypes.pptDataTypes.ppt
DataTypes.ppt
 
NoSQL.pptx
NoSQL.pptxNoSQL.pptx
NoSQL.pptx
 
NoSQL
NoSQLNoSQL
NoSQL
 
text classification_NB.ppt
text classification_NB.ppttext classification_NB.ppt
text classification_NB.ppt
 
html1.ppt
html1.ppthtml1.ppt
html1.ppt
 
slide-keras-tf.pptx
slide-keras-tf.pptxslide-keras-tf.pptx
slide-keras-tf.pptx
 
Intro_OpenCV.ppt
Intro_OpenCV.pptIntro_OpenCV.ppt
Intro_OpenCV.ppt
 
lec1b.ppt
lec1b.pptlec1b.ppt
lec1b.ppt
 
PR7.ppt
PR7.pptPR7.ppt
PR7.ppt
 
objectdetect_tutorial.ppt
objectdetect_tutorial.pptobjectdetect_tutorial.ppt
objectdetect_tutorial.ppt
 
14_ReinforcementLearning.pptx
14_ReinforcementLearning.pptx14_ReinforcementLearning.pptx
14_ReinforcementLearning.pptx
 
datamining-lect11.pptx
datamining-lect11.pptxdatamining-lect11.pptx
datamining-lect11.pptx
 
week6a.ppt
week6a.pptweek6a.ppt
week6a.ppt
 

Kürzlich hochgeladen

Ukraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSUkraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSAishani27
 
Unveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystUnveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystSamantha Rae Coolbeth
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfLars Albertsson
 
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxolyaivanovalion
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptxAnupama Kate
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...Suhani Kapoor
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxStephen266013
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFxolyaivanovalion
 
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptdokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptSonatrach
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxolyaivanovalion
 
Mature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxMature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxolyaivanovalion
 
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service AmravatiVIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service AmravatiSuhani Kapoor
 
VidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxVidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxolyaivanovalion
 
Introduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxIntroduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxfirstjob4
 
Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxolyaivanovalion
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptxthyngster
 
Call Girls In Mahipalpur O9654467111 Escorts Service
Call Girls In Mahipalpur O9654467111  Escorts ServiceCall Girls In Mahipalpur O9654467111  Escorts Service
Call Girls In Mahipalpur O9654467111 Escorts ServiceSapana Sha
 

Kürzlich hochgeladen (20)

Ukraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSUkraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICS
 
Unveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystUnveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data Analyst
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdf
 
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptx
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docx
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFx
 
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptdokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptx
 
Mature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxMature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptx
 
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service AmravatiVIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
 
VidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxVidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptx
 
Introduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxIntroduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptx
 
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
 
Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFx
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
 
Call Girls In Mahipalpur O9654467111 Escorts Service
Call Girls In Mahipalpur O9654467111  Escorts ServiceCall Girls In Mahipalpur O9654467111  Escorts Service
Call Girls In Mahipalpur O9654467111 Escorts Service
 
E-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptxE-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptx
 

Data

  • 1. Structure Query Language (SQL) Rithik Raj Vaishya Data Scientist | Corporate Trainer Dec-22 SQL 1
  • 2. SQL Introduction 2 Standard language for querying and manipulating data Structured Query Language Many standards out there: • ANSI SQL, SQL92 (a.k.a. SQL2), SQL99 (a.k.a. SQL3), …. • Vendors support various subsets: watch for fun discussions in class !
  • 3. SQL • Data Definition Language (DDL) • Create/alter/delete tables and their attributes • Following lectures... • Data Manipulation Language (DML) • Query one or more tables – discussed next ! • Insert/delete/modify tuples in tables 3
  • 4. Tables in SQL 4 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
  • 5. 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) Dec-22 SQL 5
  • 6. Data Types in SQL • Atomic types: • Characters: CHAR(20), VARCHAR(50) • Numbers: INT, BIGINT, SMALLINT, FLOAT • Others: MONEY, DATETIME, … • Every attribute must have an atomic type • Hence tables are flat • Why ? Dec-22 SQL 6
  • 7. 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(). Dec-22 SQL 7
  • 8. SQL Query Dec-22 SQL 8 Basic form: (plus many many more bells and whistles) SELECT <attributes> FROM <one or more relations> WHERE <conditions>
  • 9. Simple SQL Query Dec-22 SQL 9 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”
  • 10. Simple SQL Query Dec-22 SQL 10 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”
  • 11. Notation Dec-22 SQL 11 Product(PName, Price, Category, Manfacturer) Answer(PName, Price, Manfacturer) Input Schema Output Schema SELECT PName, Price, Manufacturer FROM Product WHERE Price > 100
  • 12. Details • Case insensitive: • Same: SELECT Select select • Same: Product product • Different: ‘Seattle’ ‘seattle’ • Constants: • ‘abc’ - yes • “abc” - no Dec-22 SQL 12
  • 13. The LIKE operator • s LIKE p: pattern matching on strings • p may contain two special symbols: • % = any sequence of characters • _ = any single character Dec-22 SQL 13 SELECT * FROM Products WHERE PName LIKE ‘%gizmo%’
  • 14. Eliminating Duplicates Dec-22 SQL 14 SELECT DISTINCT category FROM Product Compare to: SELECT category FROM Product Category Gadgets Gadgets Photography Household Category Gadgets Photography Household
  • 15. Ordering the Results Dec-22 SQL 15 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.
  • 16. 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 ? ? Dec-22 SQL 16
  • 17. Keys and Foreign Keys Dec-22 SQL 17 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
  • 18. Joins Dec-22 SQL 18 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
  • 19. Joins Dec-22 SQL 19 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
  • 20. More Joins Dec-22 SQL 20 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
  • 21. A Subtlety about Joins Dec-22 SQL 21 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
  • 22. A Subtlety about Joins Dec-22 SQL 22 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’
  • 23. Tuple Variables Dec-22 SQL 23 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
  • 24. Meaning (Semantics) of SQL Queries Dec-22 SQL 24 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
  • 25. SELECT DISTINCT R.A FROM R, S, T WHERE R.A=S.A OR R.A=T.A An Unintuitive Query Dec-22 SQL 25 Computes R  (S  T) But what if S = f ? What does it compute ?
  • 26. Subqueries Returning Relations Dec-22 SQL 26 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)
  • 27. Subqueries Returning Relations Dec-22 SQL 27 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 !
  • 28. Removing Duplicates Dec-22 SQL 28 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’
  • 29. Subqueries Returning Relations Dec-22 SQL 29 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
  • 30. Question for Database Fans and their Friends • Can we express this query as a single SELECT- FROM-WHERE query, without subqueries ? Dec-22 SQL 30
  • 31. 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 Dec-22 SQL 31
  • 32. Correlated Queries Dec-22 SQL 32 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
  • 33. 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. Dec-22 SQL 33 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);
  • 34. Aggregation Dec-22 SQL 34 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
  • 35. 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 Dec-22 SQL 35
  • 36. Purchase(product, date, price, quantity) More Examples Dec-22 SQL 36 SELECT Sum(price * quantity) FROM Purchase SELECT Sum(price * quantity) FROM Purchase WHERE product = ‘bagel’ What do they mean ?
  • 37. Simple Aggregations Dec-22 SQL 37 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)
  • 38. Grouping and Aggregation Dec-22 SQL 38 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.
  • 39. Grouping and Aggregation Dec-22 SQL 39 1. Compute the FROM and WHERE clauses. 2. Group by the attributes in the GROUPBY 3. Compute the SELECT clause: grouped attributes and aggregates.
  • 40. 1&2. FROM-WHERE-GROUPBY Dec-22 SQL 40 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
  • 41. 3. SELECT Dec-22 SQL 41 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
  • 42. GROUP BY v.s. Nested Quereis Dec-22 SQL 42 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’
  • 43. Another Example Dec-22 SQL 43 SELECT product, sum(price * quantity) AS SumSales max(quantity) AS MaxQuantity FROM Purchase GROUP BY product What does it mean ?
  • 44. HAVING Clause Dec-22 SQL 44 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.
  • 45. 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 Dec-22 SQL 45 Why ?
  • 46. General form of Grouping and Aggregation Dec-22 SQL 46 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
  • 47. Advanced SQLizing 1. Getting around INTERSECT and EXCEPT 2. Quantifiers 3. Aggregation v.s. subqueries Dec-22 SQL 47
  • 48. 1. INTERSECT and EXCEPT: Dec-22 SQL 48 (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
  • 49. 2. Quantifiers Dec-22 SQL 49 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 ! 
  • 50. 2. Quantifiers Dec-22 SQL 50 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:
  • 51. 2. Quantifiers Dec-22 SQL 51 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
  • 52. 3. Group-by v.s. Nested Query • Find authors who wrote  10 documents: • Attempt 1: with nested queries Dec-22 SQL 52 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)
  • 53. 3. Group-by v.s. Nested Query • Find all authors who wrote at least 10 documents: • Attempt 2: SQL style (with GROUP BY) Dec-22 SQL 53 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
  • 54. 3. Group-by v.s. Nested Query Dec-22 SQL 54 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)
  • 55. Two Examples Dec-22 SQL 55 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)
  • 56. 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 ? Dec-22 SQL 56
  • 57. Two Examples Dec-22 SQL 57 Store(sid, sname) Product(pid, pname, price, sid) For each store, find its most expensive product
  • 58. Two Examples Dec-22 SQL 58 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
  • 59. Two Examples Dec-22 SQL 59 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:
  • 60. 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 ? Dec-22 SQL 60
  • 61. 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 Dec-22 SQL 61
  • 62. 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 Dec-22 SQL 62 SELECT * FROM Person WHERE (age < 25) AND (height > 6 OR weight > 190) E.g. age=20 heigth=NULL weight=200
  • 63. Null Values Unexpected behavior: Some Persons are not included ! Dec-22 SQL 63 SELECT * FROM Person WHERE age < 25 OR age >= 25
  • 64. Null Values Can test for NULL explicitly: • x IS NULL • x IS NOT NULL Now it includes all Persons Dec-22 SQL 64 SELECT * FROM Person WHERE age < 25 OR age >= 25 OR age IS NULL
  • 65. Outerjoins Explicit joins in SQL = “inner joins”: Product(name, category) Purchase(prodName, store) Dec-22 SQL 65 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 !
  • 66. Outerjoins Left outer joins in SQL: Product(name, category) Purchase(prodName, store) Dec-22 SQL 66 SELECT Product.name, Purchase.store FROM Product LEFT OUTER JOIN Purchase ON Product.name = Purchase.prodName
  • 67. 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 Dec-22 SQL 67
  • 68. Application Compute, for each product, the total number of sales in ‘September’ Product(name, category) Purchase(prodName, month, store) Dec-22 SQL 68 SELECT Product.name, count(*) FROM Product, Purchase WHERE Product.name = Purchase.prodName and Purchase.month = ‘September’ GROUP BY Product.name What’s wrong ?
  • 69. Application Compute, for each product, the total number of sales in ‘September’ Product(name, category) Purchase(prodName, month, store) Dec-22 SQL 69 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
  • 70. 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 Dec-22 SQL 70
  • 71. Modifying the Database Three kinds of modifications • Insertions • Deletions • Updates Sometimes they are all called “updates” Dec-22 SQL 71
  • 72. Insertions Dec-22 SQL 72 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:
  • 73. Insertions Dec-22 SQL 73 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
  • 74. Insertion: an Example Dec-22 SQL 74 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
  • 75. Insertion: an Example Dec-22 SQL 75 INSERT INTO Product(name) SELECT DISTINCT prodName FROM Purchase WHERE prodName NOT IN (SELECT name FROM Product) name listPrice category gizmo 100 Gadgets camera - -
  • 76. Insertion: an Example Dec-22 SQL 76 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
  • 77. Deletions Dec-22 SQL 77 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:
  • 78. Updates Dec-22 SQL 78 UPDATE PRODUCT SET price = price/2 WHERE Product.name IN (SELECT product FROM Purchase WHERE Date =‘Oct, 25, 1999’); Example:
  • 80. Introduction to Relational Databases Rithik Raj Vaishya Data Scientist | Corporate Trainer
  • 81. Introduction • Database – collection of persistent data • Database Management System (DBMS) – software system that supports creation, population, and querying of a database
  • 82. Relational Database • Relational Database Management System (RDBMS) • Consists of a number of tables and single schema (definition of tables and attributes) • Students (sid, name, login, age, gpa) Students identifies the table sid, name, login, age, gpa identify attributes sid is primary key
  • 83. An Example Table • Students (sid: string, name: string, login: string, age: integer, gpa: real) sid name login age gpa 50000 Dave dave@cs 19 3.3 53666 Jones jones@cs 18 3.4 53688 Smith smith@ee 18 3.2 53650 Smith smith@math 19 3.8 53831 Madayan madayan@music 11 1.8 53832 Guldu guldu@music 12 2.0
  • 84. Another example: Courses • Courses (cid, instructor, quarter, dept) cid instructor quarter dept Carnatic101 Jane Fall 06 Music Reggae203 Bob Summer 06 Music Topology101 Mary Spring 06 Math History105 Alice Fall 06 History
  • 85. Keys • Primary key – minimal subset of fields that is unique identifier for a tuple • sid is primary key for Students • cid is primary key for Courses • Foreign key –connections between tables • Courses (cid, instructor, quarter, dept) • Students (sid, name, login, age, gpa) • How do we express which students take each course?
  • 86. Many to many relationships • In general, need a new table Enrolled(cid, grade, studid) Studid is foreign key that references sid in Student table cid grade studid Carnatic101 C 53831 Reggae203 B 53832 Topology112 A 53650 History 105 B 53666 sid name login 50000 Dave dave@cs 53666 Jones jones@cs 53688 Smith smith@ee 53650 Smith smith@math 53831 Madayan madayan@music 53832 Guldu guldu@music Enrolled Student Foreign key
  • 87. Relational Algebra • Collection of operators for specifying queries • Query describes step-by-step procedure for computing answer (i.e., operational) • Each operator accepts one or two relations as input and returns a relation as output • Relational algebra expression composed of multiple operators
  • 88. Basic operators • Selection – return rows that meet some condition • Projection – return column values • Union • Cross product • Difference • Other operators can be defined in terms of basic operators
  • 89. Example Schema (simplified) • Courses (cid, instructor, quarter, dept) • Students (sid, name, gpa) • Enrolled (cid, grade, studid)
  • 90. Selection Select students with gpa higher than 3.3 from S1: σgpa>3.3(S1) sid name gpa 50000 Dave 3.3 53666 Jones 3.4 53688 Smith 3.2 53650 Smith 3.8 53831 Madayan 1.8 53832 Guldu 2.0 S1 sid name gpa 53666 Jones 3.4 53650 Smith 3.8
  • 91. Projection Project name and gpa of all students in S1: name, gpa(S1) S1 Sid name gpa 50000 Dave 3.3 53666 Jones 3.4 53688 Smith 3.2 53650 Smith 3.8 53831 Madayan 1.8 53832 Guldu 2.0 name gpa Dave 3.3 Jones 3.4 Smith 3.2 Smith 3.8 Madayan 1.8 Guldu 2.0
  • 92. Combine Selection and Projection • Project name and gpa of students in S1 with gpa higher than 3.3: name,gpa(σgpa>3.3(S1)) Sid name gpa 50000 Dave 3.3 53666 Jones 3.4 53688 Smith 3.2 53650 Smith 3.8 53831 Madayan 1.8 53832 Guldu 2.0 name gpa Jones 3.4 Smith 3.8
  • 93. Set Operations • Union (R U S) • All tuples in R or S (or both) • R and S must have same number of fields • Corresponding fields must have same domains • Intersection (R ∩ S) • All tuples in both R and S • Set difference (R – S) • Tuples in R and not S
  • 94. Set Operations (continued) • Cross product or Cartesian product (R x S) • All fields in R followed by all fields in S • One tuple (r,s) for each pair of tuples r  R, s  S
  • 95. Example: Intersection sid name gpa 50000 Dave 3.3 53666 Jones 3.4 53688 Smith 3.2 53650 Smith 3.8 53831 Madayan 1.8 53832 Guldu 2.0 sid name gpa 53666 Jones 3.4 53688 Smith 3.2 53700 Tom 3.5 53777 Jerry 2.8 53832 Guldu 2.0 S1 S2 S1  S2 = sid name gpa 53666 Jones 3.4 53688 Smith 3.2 53832 Guldu 2.0
  • 96. Joins • Combine information from two or more tables • Example: students enrolled in courses: S1 S1.sid=E.studidE Sid name gpa 50000 Dave 3.3 53666 Jones 3.4 53688 Smith 3.2 53650 Smith 3.8 53831 Madayan 1.8 53832 Guldu 2.0 cid grade studid Carnatic101 C 53831 Reggae203 B 53832 Topology112 A 53650 History 105 B 53666 S1 E
  • 97. Joins sid name gpa cid grade studid 53666 Jones 3.4 History105 B 53666 53650 Smith 3.8 Topology112 A 53650 53831 Madayan 1.8 Carnatic101 C 53831 53832 Guldu 2.0 Reggae203 B 53832 Sid name gpa 50000 Dave 3.3 53666 Jones 3.4 53688 Smith 3.2 53650 Smith 3.8 53831 Madayan 1.8 53832 Guldu 2.0 cid grade studid Carnatic101 C 53831 Reggae203 B 53832 Topology112 A 53650 History 105 B 53666 S1 E
  • 98. Relational Algebra Summary • Algebras are useful to manipulate data types (relations in this case) • Set-oriented • Brings some clarity to what needs to be done • Opportunities for optimization • May have different expressions that do same thing • We will see examples of algebras for other types of data in this course
  • 99. Intro to SQL • CREATE TABLE • Create a new table, e.g., students, courses, enrolled • SELECT-FROM-WHERE • List all CS courses • INSERT • Add a new student, course, or enroll a student in a course
  • 100. Create Table • CREATE TABLE Enrolled (studid CHAR(20), cid CHAR(20), grade CHAR(20), PRIMARY KEY (studid, cid), FOREIGN KEY (studid) references Students)
  • 101. Select-From-Where query • “Find all students who are under 18” SELECT * FROM Students S WHERE S.age < 18
  • 102. Queries across multiple tables (joins) • “Print the student name and course ID where the student received an ‘A’ in the course” SELECT S.name, E.cid FROM Students S, Enrolled E WHERE S.sid = E.studid AND E.grade = ‘A’
  • 103. Other SQL features • MIN, MAX, AVG • Find highest grade in fall database course • COUNT, DISTINCT • How many students enrolled in CS courses in the fall? • ORDER BY, GROUP BY • Rank students by their grade in fall database course
  • 104. Views • Virtual table defined on base tables defined by a query • Single or multiple tables • Security – “hide” certain attributes from users • Show students in each course but hide their grades • Ease of use – expression that is more intuitively obvious to user • Views can be materialized to improve query performance
  • 105. Views • Suppose we often need names of students who got a ‘B’ in some course: CREATE VIEW B_Students(name, sid, course) AS SELECT S.sname, S.sid, E.cid FROM Students S, Enrolled E WHERE S.sid=E.studid and E.grade = ‘B’ name sid course Jones 53666 History105 Guldu 53832 Reggae203
  • 106. Indexes • Idea: speed up access to desired data • “Find all students with gpa > 3.3 • May need to scan entire table • Index consists of a set of entries pointing to locations of each search key
  • 107. Types of Indexes • Clustered vs. Unclustered • Clustered- ordering of data records same as ordering of data entries in the index • Unclustered- data records in different order from index • Primary vs. Secondary • Primary – index on fields that include primary key • Secondary – other indexes
  • 108. Example: Clustered Index • Sorted by sid sid name gpa 50000 Dave 3.3 53650 Smith 3.8 53666 Jones 3.4 53688 Smith 3.2 53831 Madayan 1.8 53832 Guldu 2.0 50000 53600 53800
  • 109. Example: Unclustered Index • Sorted by sid • Index on gpa sid name gpa 50000 Dave 3.3 53650 Smith 3.8 53666 Jones 3.4 53688 Smith 3.2 53831 Madayan 1.8 53832 Guldu 2.0 1.8 2.0 3.2 3.3 3.4 3.8
  • 110. Comments on Indexes • Indexes can significantly speed up query execution • But inserts more costly • May have high storage overhead • Need to choose attributes to index wisely! • What queries are run most frequently? • What queries could benefit most from an index? • Preview of things to come: SDSS
  • 111. Summary: Why are RDBMS useful? • Data independence – provides abstract view of the data, without details of storage • Efficient data access – uses techniques to store and retrieve data efficiently • Reduced application development time – many important functions already supported • Centralized data administration • Data Integrity and Security • Concurrency control and recovery
  • 112. So, why don’t scientists use them? • “I tried to use databases in my project, but they were just too [slow | hard-to-use | expensive | complex] . So I use files”. • Gray and Szalay, Where Rubber Meets the Sky: Bridging the Gap Between Databases and Science
  • 113. Some other limitations of RDBMS • Arrays • Hierarchical data
  • 114. Example: Taxonomy of Organisms • Hierarchy of categories: • Kingdom - phylum – class – order – family – genus - species • How would you design a relational schema for this? Animals Chordates Vertebrates Arthropods birds insects spiders crustaceans reptiles mammals
  • 115. NoSQL “T owards the end of RDBMS?”
  • 116. What is RDBMS  RDBMS: the relational database management system.  Relation: a relation isa 2D table which has the following features:  Name  Attributes  Tuples Name 2
  • 117. Issueswith RDBMS- Scalability  Issueswith scaling up when the dataset is just too big e.g. Big Data.  Not designed to be distributed.  Looking at multi-node database solutions. Known as ‘horizontal scaling’.  Different approaches include:  Master-slave  Sharding 3
  • 118. Scaling RDBMS Master-Slave  All writes are written to the master. All reads are performed against the replicated slave databases.  Critical reads may be incorrect as writes may not have been propagated down.  Large data sets can pose problems as master needs to duplicate data to slaves. Sharding  Scales well for both reads and writes.  Not transparent, application needs to be partition-aware.  Can nolonger have relationships or joinsacrosspartitions.  Loss of referential integrity across shards. 4
  • 119. What is NoSQL  Standsfor Not Only SQL. T ermwas redefined by Eric Evansafter Carlo Strozzi.  Class of non-relational data storage system s.  Do not require a fixed table schema nor do they use the concept of joins.  Relaxation for oneor moreof the ACIDproperties (Atomicity,Consistency, Isolation, Durability) using CAP theorem. 5
  • 120. Need of NoSQL  Explosion of social media sites (Facebook, Twitter, Google etc.) with large data needs. (Sharding isa problem)  Rise of cloud-based solutions such as Amazon S3 (simple storage solution).  Just as moving to dynamically-typed languages (Ruby/Groovy), a shift to dynamically-typed data with frequent schema changes.  Expansion of Open-source community.  NoSQL solution is more acceptable to a client now than a year ago. 6
  • 121. NoSQL T ypes NoSQL database are classified into four types: • Key Value pair based • Column based • Document based • Graph based 7
  • 122. Key Value P air Based • Designed for processing dictionary. Dictionaries contain a collection of records having fields containing data. • Records are stored and retrieved using a key that uniquely identifies the record, and is used to quickly find the data within the database. Example: CouchDB, Oracle NoSQL Database, Riak etc. We use it for storing session information, user profiles, preferences, shopping cart data. We would avoid it when we need to query data having relationships between entities. 8
  • 123. Column based It store data as Column families containing rows that have many columns associated with a row key. Each row can have different columns. Column families are groups of related data that is accessed together. Example: Cassandra, HBase, Hypertable, and Amazon DynamoDB. We use it for content management systems, blogging platforms, log aggregation. We would avoid it for systems that are in early development, changing query patterns. 9
  • 124. Document Based Thedatabase stores and retrieves documents. It stores documents in the value part of the key-value store. Self- describing, hierarchical tree data structures consisting of maps, collections, and scalar values. Example: Lotus Notes, MongoDB, Couch DB,Orient DB,Raven DB. We use it for content management systems, blogging platforms, web analytics, real-time analytics, e- commerce applications. We wouldavoid it for systemsthat need complextransactionsspanningmultiple operations or queries against varying aggregate structures. 10
  • 125. Graph Based Store entities and relationships between these entities as nodes and edges of a graph respectively. Entities have properties. Traversing the relationships is very fast as relationship between nodes is not calculated at query time but is actually persisted as a relationship. Example: Neo4J, Infinite Graph, OrientDB, FlockDB. It is well suited for connected data, such as social networks, spatial data, routing information for goods and supply. 11
  • 126. CAP Theorem  According to Eric Brewer a distributed system has3 properties :  Consistency  Availability  Partitions  We can have at most two of these three properties for any shared-data system  Toscaleout,wehaveto partition. It leaves a choicebetween consistencyand availability. ( In almost all cases, we would choose availability over consistency)  Everyonewhobuilds big applications builds themonCAP:Google, Yahoo, Facebook, Amazon, eBay, etc. 12
  • 127. Advantages of NoSQL  Cheap and easy to implement (open source)  Data are replicated to multiple nodes (therefore identical and fault- tolerant) and can be partitioned  When data is written, the latest version is on at least one node and then replicated to other nodes  No single point of failure  Easy to distribute  Don't require a schema 13
  • 128. What is not provided by NoSQL  Joins  Group by  ACID transactions  SQL  Integration with applicationsthat are based on SQL 14
  • 129. Where to use NoSQL  NoSQL Data storage systems makes sense for applications that process very large semi-structureddata –like LogAnalysis, Social Networking Feeds,Time-based data.  Toimprove programmer productivity by using a database that better matches an application's needs.  Toimprove data access performance via some combination of handling larger data volumes, reducing latency, and improving throughput. 15
  • 130. Conclusion  All the choices provided by the rise of NoSQL databases does not mean the demiseof R R elational databases are a powerful tool.  We are entering anera of Polyglot persistence,a technique that usesdifferent data stora varying data storage needs.It canapply acrossan enterprise or within an individual app 16
  • 131. R eferences 1. “NoSQL Databases: An Overview”. Pramod Sadalage, thoughtworks.com(2014) 2. “Data managementincloud environments:NoSQLand NewSQLdata stores”. Grolinger, K.; Higashino, W. A.; Tiwari, A.; Capretz, M. A. M. (2013). JoCCASA, Springer. 3. “Making the Shift from Relational to NoSQL”. Couchbase.com(2014). 4. “NoSQL- Death to R elational Databases”. Scofield, Ben (2010). 17