SlideShare ist ein Scribd-Unternehmen logo
1 von 33
1
Lecture 02: SQL
2
Outline
• Data in SQL
• Simple Queries in SQL (6.1)
• Queries with more than one relation (6.2)
Recomeded reading:
Chapter 3, “Simple Queries” from SQL for
Web Nerds, by Philip Greenspun
http://philip.greenspun.com/sql/
3
SQL Introduction
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 of these
• What we discuss is common to all of them
4
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
• Transact-SQL
– Idea: package a sequence of SQL statements  server
– Won’t discuss in class
5
Data in SQL
1. Atomic types, a.k.a. data types
2. Tables built from atomic types
Unlike XML, no nested tables, only flat tables are
allowed!
– We will see later how to decompose complex
structures into multiple flat tables
6
Data Types in SQL
• Characters:
– CHAR(20) -- fixed length
– VARCHAR(40) -- variable length
• Numbers:
– BIGINT, INT, SMALLINT, TINYINT
– REAL, FLOAT -- differ in precision
– MONEY
• Times and dates:
– DATE
– DATETIME -- SQL Server
• Others... All are simple
7
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
8
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 unordered: no first(), no next(), no last().
9
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)
10
SQL Query
Basic form: (plus many many more bells and whistles)
SELECT attributes
FROM relations (possibly multiple)
WHERE conditions (selections)
11
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”
12
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”
13
A Notation for SQL Queries
SELECT PName, Price, Manufacturer
FROM Product
WHERE Price > 100
Product(PName, Price, Category, Manfacturer)
Answer(PName, Price, Manfacturer)
Input Schema
Output Schema
14
Selections
What goes in the WHERE clause:
• x = y, x < y, x <= y, etc
– For number, they have the usual meanings
– For CHAR and VARCHAR: lexicographic ordering
• Expected conversion between CHAR and VARCHAR
– For dates and times, what you expect...
• Pattern matching on strings...
15
The LIKE operator
• s LIKE p: pattern matching on strings
• p may contain two special symbols:
– % = any sequence of characters
– _ = any single character
Product(PName, Price, Category, Manufacturer)
Find all products whose name mentions ‘gizmo’:
SELECT *
FROM Products
WHERE PName LIKE ‘%gizmo%’
16
Eliminating Duplicates
SELECT DISTINCT category
FROM Product
Compare to:
SELECT category
FROM Product
Category
Gadgets
Gadgets
Photography
Household
Category
Gadgets
Photography
Household
17
Ordering the Results
SELECT pname, price, manufacturer
FROM Product
WHERE category=‘gizmo’AND price > 50
ORDER BY price, pname
Ordering is ascending, unless you specify the DESC keyword.
Ties are broken by the second attribute on the ORDER BY list, etc.
18
Ordering the Results
SELECT category
FROM Product
ORDER BY pname
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
?
19
Ordering the Results
SELECT DISTINCT category
FROM Product
ORDER BY category
Compare to:
Category
Gadgets
Household
Photography
SELECT category
FROM Product
ORDER BY pname ?
20
Joins in SQL
• Connect two or more tables:
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
What is
the connection
between
them ?
21
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
22
Joins 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
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
23
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’
24
Joins in SQL
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
SELECT country
FROM Product, Company
WHERE manufacturer=cname AND category=‘Gadgets’
Country
??
??
What is
the problem ?
What’s the
solution ?
25
Joins
Product (pname, price, category, manufacturer)
Purchase (buyer, seller, store, product)
Person(persname, phoneNumber, city)
Find names of people living in Seattle that bought some
product in the ‘Gadgets’ category, and the names of the
stores they bought such product from
SELECT DISTINCT persname, store
FROM Person, Purchase, Product
WHERE persname=buyer AND product = pname AND
city=‘Seattle’ AND category=‘Gadgets’
26
When are two tables related?
• You guess they are
• I tell you so
• Foreign keys are a method for schema designers to
tell you so (7.1)
– A foreign key states that a column is a reference to the
key of another table
ex: Product.manufacturer is foreign key of Company
– Gives information and enforces constraint
27
Disambiguating Attributes
• Sometimes two relations have the same attr:
Person(pname, address, worksfor)
Company(cname, address)
SELECT DISTINCT pname, address
FROM Person, Company
WHERE worksfor = cname
SELECT DISTINCT Person.pname, Company.address
FROM Person, Company
WHERE Person.worksfor = Company.cname
Which
address ?
28
Tuple Variables
SELECT DISTINCT x.store
FROM Purchase AS x, Purchase AS y
WHERE x.product = y.product AND y.store = ‘BestBuy’
Find all stores that sold at least one product that the store
‘BestBuy’ also sold:
Answer (store)
Product (pname, price, category, manufacturer)
Purchase (buyer, seller, store, product)
Person(persname, phoneNumber, city)
29
Tuple Variables
General rule:
tuple variables introduced automatically by the system:
Product (name, price, category, manufacturer)
Becomes:
Doesn’t work when Product occurs more than once:
In that case the user needs to define variables explicitly.
SELECT name
FROM Product
WHERE price > 100
SELECT Product.name
FROM Product AS Product
WHERE Product.price > 100
30
Meaning (Semantics) of SQL
Queries
SELECT a1, a2, …, ak
FROM R1 AS x1, R2 AS x2, …, Rn AS xn
WHERE Conditions
1. Nested loops:
Answer = {}
for x1 in R1 do
for x2 in R2 do
…..
for xn in Rn do
if Conditions
then Answer = Answer  {(a1,…,ak)}
return Answer
31
Meaning (Semantics) of SQL
Queries
SELECT a1, a2, …, ak
FROM R1 AS x1, R2 AS x2, …, Rn AS xn
WHERE Conditions
2. Parallel assignment
Doesn’t impose any order !
Answer = {}
for all assignments x1 in R1, …, xn in Rn do
if Conditions then Answer = Answer  {(a1,…,ak)}
return Answer
32
First Unintuitive SQLism
SELECT R.A
FROM R, S, T
WHERE R.A=S.A OR R.A=T.A
Looking for R (S T)
But what happens if T is empty?
 
33
Exercises
Product (pname, price, category, manufacturer)
Purchase (buyer, seller, store, product)
Company (cname, stock price, country)
Person(per-name, phone number, city)
Ex #1: Find people who bought telephony products.
Ex #2: Find names of people who bought American products
Ex #3: Find names of people who bought American products and they
live in Seattle.
Ex #4: Find people who have both bought and sold something.
Ex #5: Find people who bought stuff from Joe or bought products
from a company whose stock prices is more than $50.

Weitere ähnliche Inhalte

Ähnlich wie sql-basic.ppt

Ähnlich wie sql-basic.ppt (20)

lecture-sql.ppt
lecture-sql.pptlecture-sql.ppt
lecture-sql.ppt
 
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
 
Slides 2-basic sql
Slides 2-basic sqlSlides 2-basic sql
Slides 2-basic sql
 
Sql introduction
Sql introductionSql introduction
Sql introduction
 
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 structure query language full presentation
SQL structure query language full presentationSQL structure query language full presentation
SQL structure query language full presentation
 
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
 
Sql for biggner
Sql for biggnerSql for biggner
Sql for biggner
 
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
 
Xamppinstallation edited
Xamppinstallation editedXamppinstallation edited
Xamppinstallation edited
 
Sql
SqlSql
Sql
 
SQL
SQL SQL
SQL
 
2018 03 27_biological_databases_part4_v_upload
2018 03 27_biological_databases_part4_v_upload2018 03 27_biological_databases_part4_v_upload
2018 03 27_biological_databases_part4_v_upload
 

Mehr von wondmhunegn

Microsoft Access.ppt
Microsoft Access.pptMicrosoft Access.ppt
Microsoft Access.pptwondmhunegn
 
Module 2 Slides.ppt
Module 2 Slides.pptModule 2 Slides.ppt
Module 2 Slides.pptwondmhunegn
 
ETE105_lecture 3.ppt
ETE105_lecture 3.pptETE105_lecture 3.ppt
ETE105_lecture 3.pptwondmhunegn
 
BasicComputerParts.ppt
BasicComputerParts.pptBasicComputerParts.ppt
BasicComputerParts.pptwondmhunegn
 
Chapter 1 Data structure.pptx
Chapter 1 Data structure.pptxChapter 1 Data structure.pptx
Chapter 1 Data structure.pptxwondmhunegn
 
IS230 - Chapter 4 - Keys and Relationship - Revised.ppt
IS230 - Chapter 4 - Keys and Relationship - Revised.pptIS230 - Chapter 4 - Keys and Relationship - Revised.ppt
IS230 - Chapter 4 - Keys and Relationship - Revised.pptwondmhunegn
 
MS-Access Tables Forms Queries Reports.ppt
MS-Access Tables Forms Queries Reports.pptMS-Access Tables Forms Queries Reports.ppt
MS-Access Tables Forms Queries Reports.pptwondmhunegn
 
DatabaseFundamentals.ppt
DatabaseFundamentals.pptDatabaseFundamentals.ppt
DatabaseFundamentals.pptwondmhunegn
 
Data Types and Field Properties.ppt
Data Types and Field Properties.pptData Types and Field Properties.ppt
Data Types and Field Properties.pptwondmhunegn
 

Mehr von wondmhunegn (11)

Microsoft Access.ppt
Microsoft Access.pptMicrosoft Access.ppt
Microsoft Access.ppt
 
Module 2 Slides.ppt
Module 2 Slides.pptModule 2 Slides.ppt
Module 2 Slides.ppt
 
ETE105_lecture 3.ppt
ETE105_lecture 3.pptETE105_lecture 3.ppt
ETE105_lecture 3.ppt
 
BasicComputerParts.ppt
BasicComputerParts.pptBasicComputerParts.ppt
BasicComputerParts.ppt
 
tree.ppt
tree.ppttree.ppt
tree.ppt
 
Chapter 1 Data structure.pptx
Chapter 1 Data structure.pptxChapter 1 Data structure.pptx
Chapter 1 Data structure.pptx
 
IS230 - Chapter 4 - Keys and Relationship - Revised.ppt
IS230 - Chapter 4 - Keys and Relationship - Revised.pptIS230 - Chapter 4 - Keys and Relationship - Revised.ppt
IS230 - Chapter 4 - Keys and Relationship - Revised.ppt
 
MS-Access Tables Forms Queries Reports.ppt
MS-Access Tables Forms Queries Reports.pptMS-Access Tables Forms Queries Reports.ppt
MS-Access Tables Forms Queries Reports.ppt
 
DatabaseFundamentals.ppt
DatabaseFundamentals.pptDatabaseFundamentals.ppt
DatabaseFundamentals.ppt
 
Data Types and Field Properties.ppt
Data Types and Field Properties.pptData Types and Field Properties.ppt
Data Types and Field Properties.ppt
 
Template.pptx
Template.pptxTemplate.pptx
Template.pptx
 

Kürzlich hochgeladen

Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...amitlee9823
 
Edukaciniai dropshipping via API with DroFx
Edukaciniai dropshipping via API with DroFxEdukaciniai dropshipping via API with DroFx
Edukaciniai dropshipping via API with DroFxolyaivanovalion
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...amitlee9823
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxolyaivanovalion
 
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779Delhi Call girls
 
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...amitlee9823
 
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightCheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightDelhi Call girls
 
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
 
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
 
Data-Analysis for Chicago Crime Data 2023
Data-Analysis for Chicago Crime Data  2023Data-Analysis for Chicago Crime Data  2023
Data-Analysis for Chicago Crime Data 2023ymrp368
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% SecurePooja Nehwal
 
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
 
Ravak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxRavak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxolyaivanovalion
 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfRachmat Ramadhan H
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFxolyaivanovalion
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysismanisha194592
 
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
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
BigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxBigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxolyaivanovalion
 

Kürzlich hochgeladen (20)

Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
 
Edukaciniai dropshipping via API with DroFx
Edukaciniai dropshipping via API with DroFxEdukaciniai dropshipping via API with DroFx
Edukaciniai dropshipping via API with DroFx
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptx
 
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
 
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
 
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightCheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
 
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
 
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
 
Data-Analysis for Chicago Crime Data 2023
Data-Analysis for Chicago Crime Data  2023Data-Analysis for Chicago Crime Data  2023
Data-Analysis for Chicago Crime Data 2023
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
 
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
 
Ravak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxRavak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptx
 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFx
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysis
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
 
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
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
BigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxBigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptx
 

sql-basic.ppt

  • 2. 2 Outline • Data in SQL • Simple Queries in SQL (6.1) • Queries with more than one relation (6.2) Recomeded reading: Chapter 3, “Simple Queries” from SQL for Web Nerds, by Philip Greenspun http://philip.greenspun.com/sql/
  • 3. 3 SQL Introduction 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 of these • What we discuss is common to all of them
  • 4. 4 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 • Transact-SQL – Idea: package a sequence of SQL statements  server – Won’t discuss in class
  • 5. 5 Data in SQL 1. Atomic types, a.k.a. data types 2. Tables built from atomic types Unlike XML, no nested tables, only flat tables are allowed! – We will see later how to decompose complex structures into multiple flat tables
  • 6. 6 Data Types in SQL • Characters: – CHAR(20) -- fixed length – VARCHAR(40) -- variable length • Numbers: – BIGINT, INT, SMALLINT, TINYINT – REAL, FLOAT -- differ in precision – MONEY • Times and dates: – DATE – DATETIME -- SQL Server • Others... All are simple
  • 7. 7 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
  • 8. 8 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 unordered: no first(), no next(), no last().
  • 9. 9 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)
  • 10. 10 SQL Query Basic form: (plus many many more bells and whistles) SELECT attributes FROM relations (possibly multiple) WHERE conditions (selections)
  • 11. 11 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”
  • 12. 12 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”
  • 13. 13 A Notation for SQL Queries SELECT PName, Price, Manufacturer FROM Product WHERE Price > 100 Product(PName, Price, Category, Manfacturer) Answer(PName, Price, Manfacturer) Input Schema Output Schema
  • 14. 14 Selections What goes in the WHERE clause: • x = y, x < y, x <= y, etc – For number, they have the usual meanings – For CHAR and VARCHAR: lexicographic ordering • Expected conversion between CHAR and VARCHAR – For dates and times, what you expect... • Pattern matching on strings...
  • 15. 15 The LIKE operator • s LIKE p: pattern matching on strings • p may contain two special symbols: – % = any sequence of characters – _ = any single character Product(PName, Price, Category, Manufacturer) Find all products whose name mentions ‘gizmo’: SELECT * FROM Products WHERE PName LIKE ‘%gizmo%’
  • 16. 16 Eliminating Duplicates SELECT DISTINCT category FROM Product Compare to: SELECT category FROM Product Category Gadgets Gadgets Photography Household Category Gadgets Photography Household
  • 17. 17 Ordering the Results SELECT pname, price, manufacturer FROM Product WHERE category=‘gizmo’AND price > 50 ORDER BY price, pname Ordering is ascending, unless you specify the DESC keyword. Ties are broken by the second attribute on the ORDER BY list, etc.
  • 18. 18 Ordering the Results SELECT category FROM Product ORDER BY pname PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi ?
  • 19. 19 Ordering the Results SELECT DISTINCT category FROM Product ORDER BY category Compare to: Category Gadgets Household Photography SELECT category FROM Product ORDER BY pname ?
  • 20. 20 Joins in SQL • Connect two or more tables: 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 What is the connection between them ?
  • 21. 21 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
  • 22. 22 Joins 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 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
  • 23. 23 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’
  • 24. 24 Joins in SQL 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 SELECT country FROM Product, Company WHERE manufacturer=cname AND category=‘Gadgets’ Country ?? ?? What is the problem ? What’s the solution ?
  • 25. 25 Joins Product (pname, price, category, manufacturer) Purchase (buyer, seller, store, product) Person(persname, phoneNumber, city) Find names of people living in Seattle that bought some product in the ‘Gadgets’ category, and the names of the stores they bought such product from SELECT DISTINCT persname, store FROM Person, Purchase, Product WHERE persname=buyer AND product = pname AND city=‘Seattle’ AND category=‘Gadgets’
  • 26. 26 When are two tables related? • You guess they are • I tell you so • Foreign keys are a method for schema designers to tell you so (7.1) – A foreign key states that a column is a reference to the key of another table ex: Product.manufacturer is foreign key of Company – Gives information and enforces constraint
  • 27. 27 Disambiguating Attributes • Sometimes two relations have the same attr: Person(pname, address, worksfor) Company(cname, address) SELECT DISTINCT pname, address FROM Person, Company WHERE worksfor = cname SELECT DISTINCT Person.pname, Company.address FROM Person, Company WHERE Person.worksfor = Company.cname Which address ?
  • 28. 28 Tuple Variables SELECT DISTINCT x.store FROM Purchase AS x, Purchase AS y WHERE x.product = y.product AND y.store = ‘BestBuy’ Find all stores that sold at least one product that the store ‘BestBuy’ also sold: Answer (store) Product (pname, price, category, manufacturer) Purchase (buyer, seller, store, product) Person(persname, phoneNumber, city)
  • 29. 29 Tuple Variables General rule: tuple variables introduced automatically by the system: Product (name, price, category, manufacturer) Becomes: Doesn’t work when Product occurs more than once: In that case the user needs to define variables explicitly. SELECT name FROM Product WHERE price > 100 SELECT Product.name FROM Product AS Product WHERE Product.price > 100
  • 30. 30 Meaning (Semantics) of SQL Queries SELECT a1, a2, …, ak FROM R1 AS x1, R2 AS x2, …, Rn AS xn WHERE Conditions 1. Nested loops: Answer = {} for x1 in R1 do for x2 in R2 do ….. for xn in Rn do if Conditions then Answer = Answer  {(a1,…,ak)} return Answer
  • 31. 31 Meaning (Semantics) of SQL Queries SELECT a1, a2, …, ak FROM R1 AS x1, R2 AS x2, …, Rn AS xn WHERE Conditions 2. Parallel assignment Doesn’t impose any order ! Answer = {} for all assignments x1 in R1, …, xn in Rn do if Conditions then Answer = Answer  {(a1,…,ak)} return Answer
  • 32. 32 First Unintuitive SQLism SELECT R.A FROM R, S, T WHERE R.A=S.A OR R.A=T.A Looking for R (S T) But what happens if T is empty?  
  • 33. 33 Exercises Product (pname, price, category, manufacturer) Purchase (buyer, seller, store, product) Company (cname, stock price, country) Person(per-name, phone number, city) Ex #1: Find people who bought telephony products. Ex #2: Find names of people who bought American products Ex #3: Find names of people who bought American products and they live in Seattle. Ex #4: Find people who have both bought and sold something. Ex #5: Find people who bought stuff from Joe or bought products from a company whose stock prices is more than $50.