SlideShare uma empresa Scribd logo
1 de 32
SQL
Higher Computing Science
CAR HIRE DATABASE EXAMPLE
• The following SQL query examples will relate to a car hire database
which consists of 4 tables:
Customer Booking Car Depot
places contain
s
is stored at
CAR HIRE DATABASE EXAMPLE
• The following SQL query examples will relate to a car hire database
which consists of 4 tables:
Customer
customerID
forename
surname
telephone
houseNum
postcode
Booking
bookingRef
customerID *
registration *
daysBooked
startDate
Car
registration
make
model
colour
depotID *
automatic
dailyPrice
mileage
Depot
depotID
depotName
depotCity
onlineBookin
g
depotHours
employees
WILDCARDS
• A wildcard is a symbol used to replace or represent one or more
characters.
• SQL wildcards are used with the LIKE operator.
• % wildcard – matches one or more characters
• _ wildcard – matches exactly one character
• (Note that Microsoft Access uses
• * in place of %,
• ? In place of _
WILDCARDS EXAMPLE 1
• Write an SQL query to display the make, model and mileage of a car in a
depot which is open all day, and where the make of car starts with ‘M’.
SELECT make, model, mileage, depotName, depotHours
FROM car, depot
WHERE depotHours = 'All Day' and make LIKE ‘M%'
AND car.depotID = depot.depotID;
WILDCARDS EXAMPLE 1
• Write an SQL query to display the make, model and mileage of a car in a
depot which is open all day, and where the make of car starts with ‘M’.
make model mileag
e
depotName depotHours
Mazda 3 19210 Summerville
Street
All Day
Mercede
s
A-
Class
30043 Summerville
Street
All Day
Mazda 3 84662 Smith’s Garage All Day
WILDCARDS EXAMPLE 2
• Write an SQL query to display a customer’s full name, booking ID, car make and
model, and depot name for all customers who have ‘e’ as the 5th letter of their
surname
• List the details in alphabetical order of the customer surname
SELECT forename, surname, bookingRef, make, model, depotName
FROM customer, booking, car, depot
WHERE surname LIKE ‘____e%'
AND customer.customerID = booking.customerID
AND booking.registration = car.registration
AND car.depotID = depot.depotID
ORDER BY surname;
WILDCARDS EXAMPLE 2
• Write an SQL query to display a customer’s full name, booking ID, car
make and model, and depot name for all customers who have ‘e’ as the
5th letter of their surname
• List the details in alphabetical order of the customer surname
forenam
e
surname bookingRe
f
make model depotName
Leanne Docherty B3648 Volkswage
n
Polo Machine Works
Mike Fraser B3658 Volkswage
n
Golf Castle
Mike Fraser B3481 Volkswage
n
Golf Summerville
Street
Stephen Grimes B3660 Volkswage Golf Castle
AVG
• The AVG() function returns the average value of a numeric column.
• Write an SQL query to display the average mileage of all the cars in the car table.
SELECT AVG(mileage)
FROM car;
AVG
avg
28950.95
• The AVG() function returns the average value of a numeric column.
• Write an SQL query to display the average mileage of all the cars in the car table.
MIN, MAX & ALIASES
• The MIN() and MAX functions returns the largest and smallest values of a numeric
column.
• Aliases can be used to give columns a more readable name. The SQL AS statement
does this.
• Write an SQL query to display the lowest and highest mileages of the cars in the
car table. The result should have a readable heading.
SELECT MIN(mileage) AS [Lowest Mileage], MAX(mileage) AS
[Highest Mileage]
FROM car;
MIN, MAX & ALIASES
• The MIN() and MAX functions returns the largest and smallest values of a numeric
column.
• Aliases can be used to give columns a more readable name. The SQL AS statement
does this.
• Write an SQL query to display the lowest and highest mileages of the cars in the
car table. The result should have a readable heading.
Lowest Mileage Highest
Mileage
6979 102300
COUNT
• The COUNT() function returns the number of rows that match a specified criteria.
• Write an SQL query to display the cities that have depot, together with the number
of depots in each city.
SELECT depotCity, COUNT(*)
FROM depot
GROUP BY depotCity;
depotCity count
Edinburgh 3
Glasgow 2
Inverness 1
Perth 1
COUNT
• The COUNT() function returns the number of rows that match a specified criteria.
• Write an SQL query to display the cities that have depot, together with the number
of depots in each city.
SUM
• The SUM() function returns the sum of a numeric column.
• Write an SQL query to display the number of employees that are based in depots
in Edinburgh or Glasgow. Use ‘Edinburgh/Glasgow Employees’ as a readable
heading.
SELECT SUM(employees) AS [Edinburgh/Glasgow Employees]
FROM depot
WHERE depotCity = 'Edinburgh'
OR depotCity = 'Glasgow';
SUM
• The SUM() function returns the sum of a numeric column.
• Write an SQL query to display the number of employees that are based in depots
in Edinburgh or Glasgow. Use ‘Edinburgh/Glasgow Employees’ as a readable
heading.
Edinburgh/Glasgow
Employees
36
GROUP BY
• The GROUP BY statement groups rows with the same values together.
• Write an SQL query to display a list of each car colour, together with the number of
bookings made for cars of those colours.
• List the details from the least popular colour to the most popular colour.
SELECT colour, COUNT(*)
FROM car, booking
WHERE booking.registration = car.registration
GROUP BY colour
ORDER BY COUNT(*) ASC;
GROUP BY
• The GROUP BY statement groups rows with the same values together.
• Write an SQL query to display a list of each car colour, together with the number of
bookings made for cars of those colours.
• List the details from the least popular colour to the most popular colour.
colour count
Blue 1
Red 2
Black 4
Sliver 5
White 6
UPDATE
• The UDPATE command can be used to update the values of more than one field.
• The details of the car with registration BA18 HER have changed, use SQL to update
the car record as follows:
• mileage = 21540
• dailyPrice = 38
UPDATE car
SET mileage = 21540, dailyPrice = 38
WHERE registration = 'BA18 HER';
UPDATE
• The UDPATE command can be used to update the values of more than one field.
• The details of the car with registration BA18 HER have changed, use SQL to update
the car record as follows:
• mileage = 21540
• dailyPrice = £38.00
registratio
n
make model colour depotID automati
c
dailyPric
e
mileage
BA18 HER Volkswage
n
Golf Black D1004  £40.00 21233
registratio
n
make model colour depotID automati
c
dailyPric
e
mileage
BA18 HER Volkswage
n
Golf Black D1004  £38.00 21540
COMPUTED VALUES
• A computed value is a calculation within a SELECT statement.
• Write an SQL query to display the surname, booking reference, number of days
booked, daily price, and a calculated total cost of each booking (with a readable
column heading).
• Display the most expensive booking first.
SELECT surname, bookingRef, daysBooked, dailyPrice,
daysBooked * dailyPrice AS [Total Cost]
FROM customer, booking, car
WHERE customer.customerID = booking.customerID
AND booking.registration = car.registration
ORDER BY daysBooked * dailyPrice DESC;
COMPUTED VALUES
• Write an SQL query to display the surname, booking reference, number of days
booked, daily price, and a calculated total cost of each booking (with a readable
column heading).
• Display the most expensive booking first.
surname bookingRe
f
daysBooke
d
dailyPric
e
Total Cost
Grimes B3660 6 £42.00 £252.00
MacArthur B3655 7 £33.00 £231.00
Green B3524 5 £41.00 £205.00
Li B3578 4 £42.00 £168.00
Watson B3562 3 £52.00 £156.00
Fraser B3481 3 £38.00 £114.00
Gorecki B3537 1 £40.00 £40.00
USING THE RESULT OF A QUERY
• The result of a query can be used as a table in a second query.
• Write an SQL query to display the name of depots that have cars with the cheapest
daily price together with the price (use a readable heading to display the cheapest
price).
• This solution will require two separate queries:
• Query 1: a simple query to generate a single value (the cheapest daily price)
• Query 2: uses Query 1 to find the depots with the cheapest daily price
USING THE RESULT OF A QUERY
• Write an SQL query to display the name of depots that have cars with the cheapest
daily price together with the price (use a readable heading to display the cheapest
price).
Query 1 – Find Minimum Daily Price
SELECT MIN(dailyPrice) AS [Cheapest Daily Price]
FROM car;
USING THE RESULT OF A QUERY
• Write an SQL query to display the name of depots that have cars with the cheapest
daily price together with the price (use a readable heading to display the cheapest
price).
Query 1 – Find Minimum Daily Price
Cheapest Daily
Price
£21.00
USING THE RESULT OF A QUERY
• Write an SQL query to display the name of depots that have cars with the cheapest
daily price together with the price (use a readable heading to display the cheapest
price).
Query 2 – Display names of depots with cars at cheapest daily price
SELECT depotName, [Cheapest Daily Price]
FROM car, depot, [Find Minimum Daily Price]
WHERE dailyPrice = [Cheapest Daily Price]
AND car.depotID = depot.depotID;
USING THE RESULT OF A QUERY
• Write an SQL query to display the name of depots that have cars with the cheapest
daily price together with the price (use a readable heading to display the cheapest
price).
Query 2 – Display names of depots with cars at cheapest daily price
depotName Cheapest Daily Price
Smith’s Garage £21.00
Green Place £21.00
Machine Works £21.00
USING THE RESULT OF A QUERY
Second Example:
• Write an SQL query to display the details of any automatic car with a daily price
that is above the average daily price. The query should display the car make,
model, colour, automatic and daily price.
• The most expensive cars should be listed first.
• This solution requires two separate queries.
• Query 1: a simple query to generate a single value (the average daily price)
• Query 2: uses Query 1 to find the automatic cars that are above the average daily price
USING THE RESULT OF A QUERY
Second Example:
• Write an SQL query to display the details of any automatic car with a daily price
that is above the average daily price. The query should display the car make,
model, colour, automatic and daily price. The most expensive cars should be listed
first.
Query 1 – Find Average Daily Price
SELECT AVG(dailyPrice) AS [Average Daily Price]
FROM car;
USING THE RESULT OF A QUERY
Second Example:
• Write an SQL query to display the details of any automatic car with a daily price
that is above the average daily price. The query should display the car make,
model, colour, automatic and daily price. The most expensive cars should be listed
first.
Query 1 – Find Average Daily Price
Average Daily Price
£34.68
USING THE RESULT OF A QUERY
Second Example:
• Write an SQL query to display the details of any automatic car with a daily price
that is above the average daily price. The query should display the car make,
model, colour, automatic and daily price. The most expensive cars should be listed
first.
Query 2 – Display automatic cars with daily price above average daily price
SELECT make, model, colour, automatic, dailyPrice, [Average
Daily Price]
FROM car, [Find Average Daily Price]
WHERE dailyPrice > [Average Daily Price]
AND automatic = TRUE
USING THE RESULT OF A QUERY
Second Example:
• Write an SQL query to display the details of any automatic car with a daily price
that is above the average daily price. The query should display the car make,
model, colour, automatic and daily price. The most expensive cars should be listed
first.
Query 2 – Display automatic cars with daily price above average daily price
make model colour automati
c
dailyPric
e
Average Daily
Price
Mercedes A-Class Red  £52.00 £34.68
Nissan Qashqa
i
Silver  £46.00 £34.68
Volkswage Golf Black  £37.00 £34.68

Mais conteúdo relacionado

Mais procurados

Triggers in plsql
Triggers in plsqlTriggers in plsql
Triggers in plsqlArun Sial
 
SQL Oracle : Sélection et Tri des Lignes Retournées par un SELECT
SQL Oracle : Sélection et Tri des Lignes Retournées par un SELECTSQL Oracle : Sélection et Tri des Lignes Retournées par un SELECT
SQL Oracle : Sélection et Tri des Lignes Retournées par un SELECTwebreaker
 
Sql Basics | Edureka
Sql Basics | EdurekaSql Basics | Edureka
Sql Basics | EdurekaEdureka!
 
Intro to SQL for Beginners
Intro to SQL for BeginnersIntro to SQL for Beginners
Intro to SQL for BeginnersProduct School
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptxSherinRappai
 
MySQL developing Store Procedure
MySQL developing Store ProcedureMySQL developing Store Procedure
MySQL developing Store ProcedureMarco Tusa
 
04 Handling Exceptions
04 Handling Exceptions04 Handling Exceptions
04 Handling Exceptionsrehaniltifat
 
Kicking ass with redis
Kicking ass with redisKicking ass with redis
Kicking ass with redisDvir Volk
 
SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredDanish Mehraj
 
Using Search API, Search API Solr and Facets in Drupal 8
Using Search API, Search API Solr and Facets in Drupal 8Using Search API, Search API Solr and Facets in Drupal 8
Using Search API, Search API Solr and Facets in Drupal 8Websolutions Agency
 
SQL For Dummies
SQL For DummiesSQL For Dummies
SQL For Dummiesomenar
 
Method Handles in Java
Method Handles in JavaMethod Handles in Java
Method Handles in Javahendersk
 

Mais procurados (20)

Triggers in plsql
Triggers in plsqlTriggers in plsql
Triggers in plsql
 
Sql joins
Sql joinsSql joins
Sql joins
 
SQL Oracle : Sélection et Tri des Lignes Retournées par un SELECT
SQL Oracle : Sélection et Tri des Lignes Retournées par un SELECTSQL Oracle : Sélection et Tri des Lignes Retournées par un SELECT
SQL Oracle : Sélection et Tri des Lignes Retournées par un SELECT
 
Subqueries
SubqueriesSubqueries
Subqueries
 
Sql Basics | Edureka
Sql Basics | EdurekaSql Basics | Edureka
Sql Basics | Edureka
 
Sql functions
Sql functionsSql functions
Sql functions
 
Intro to SQL for Beginners
Intro to SQL for BeginnersIntro to SQL for Beginners
Intro to SQL for Beginners
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
 
MySQL developing Store Procedure
MySQL developing Store ProcedureMySQL developing Store Procedure
MySQL developing Store Procedure
 
04 Handling Exceptions
04 Handling Exceptions04 Handling Exceptions
04 Handling Exceptions
 
SQL UNION
SQL UNIONSQL UNION
SQL UNION
 
Kicking ass with redis
Kicking ass with redisKicking ass with redis
Kicking ass with redis
 
SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics Covered
 
8. sql
8. sql8. sql
8. sql
 
advanced sql(database)
advanced sql(database)advanced sql(database)
advanced sql(database)
 
Using Search API, Search API Solr and Facets in Drupal 8
Using Search API, Search API Solr and Facets in Drupal 8Using Search API, Search API Solr and Facets in Drupal 8
Using Search API, Search API Solr and Facets in Drupal 8
 
SQL For Dummies
SQL For DummiesSQL For Dummies
SQL For Dummies
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
 
Sql - Structured Query Language
Sql - Structured Query LanguageSql - Structured Query Language
Sql - Structured Query Language
 
Method Handles in Java
Method Handles in JavaMethod Handles in Java
Method Handles in Java
 

Semelhante a SQL

Semantic search in databases
Semantic search in databasesSemantic search in databases
Semantic search in databasesTomáš Drenčák
 
MongoDB World 2016 : Advanced Aggregation
MongoDB World 2016 : Advanced AggregationMongoDB World 2016 : Advanced Aggregation
MongoDB World 2016 : Advanced AggregationJoe Drumgoole
 
R, Scikit-Learn and Apache Spark ML - What difference does it make?
R, Scikit-Learn and Apache Spark ML - What difference does it make?R, Scikit-Learn and Apache Spark ML - What difference does it make?
R, Scikit-Learn and Apache Spark ML - What difference does it make?Villu Ruusmann
 
Data Analytics Project Presentation
Data Analytics Project PresentationData Analytics Project Presentation
Data Analytics Project PresentationRohit Vaze
 
YearQuarterLocationCarClassRevenue NumCars 2017Q1Downt.docx
YearQuarterLocationCarClassRevenue  NumCars  2017Q1Downt.docxYearQuarterLocationCarClassRevenue  NumCars  2017Q1Downt.docx
YearQuarterLocationCarClassRevenue NumCars 2017Q1Downt.docxadampcarr67227
 
http://boxinglatestnews.com
http://boxinglatestnews.comhttp://boxinglatestnews.com
http://boxinglatestnews.comDavid Lopez
 
Using machine learning to generate predictions based on the information extra...
Using machine learning to generate predictions based on the information extra...Using machine learning to generate predictions based on the information extra...
Using machine learning to generate predictions based on the information extra...University Politehnica Bucharest
 
Predicting model for prices of used cars
Predicting model for prices of used carsPredicting model for prices of used cars
Predicting model for prices of used carsHARPREETSINGH1862
 
CARVANA - Predicting the purchase quality in car
CARVANA - Predicting the  purchase quality in carCARVANA - Predicting the  purchase quality in car
CARVANA - Predicting the purchase quality in carShankarPrasaadRajama
 
2003 DODGE RAM TRUCK Service Repair Manual
2003 DODGE RAM TRUCK Service Repair Manual2003 DODGE RAM TRUCK Service Repair Manual
2003 DODGE RAM TRUCK Service Repair Manualjksemd dysjekmdm
 
2003 DODGE RAM TRUCK Service Repair Manual
2003 DODGE RAM TRUCK Service Repair Manual2003 DODGE RAM TRUCK Service Repair Manual
2003 DODGE RAM TRUCK Service Repair Manualjdksmemd
 
The select statement
The select statementThe select statement
The select statementpunu_82
 
Patterns and practices for real-world event-driven microservices by Rachel Re...
Patterns and practices for real-world event-driven microservices by Rachel Re...Patterns and practices for real-world event-driven microservices by Rachel Re...
Patterns and practices for real-world event-driven microservices by Rachel Re...Codemotion Dubai
 
Patterns and practices for real-world event-driven microservices
Patterns and practices for real-world event-driven microservicesPatterns and practices for real-world event-driven microservices
Patterns and practices for real-world event-driven microservicesRachel Reese
 
mercedes benz training presentation
mercedes benz training presentationmercedes benz training presentation
mercedes benz training presentationMunish Kumar
 
Software Engineer Screening Question - OOP
Software Engineer Screening Question - OOPSoftware Engineer Screening Question - OOP
Software Engineer Screening Question - OOPjason_scorebig
 
Data Warehouse and OLAP - Lear-Fabini
Data Warehouse and OLAP - Lear-FabiniData Warehouse and OLAP - Lear-Fabini
Data Warehouse and OLAP - Lear-FabiniScott Fabini
 

Semelhante a SQL (20)

Semantic search in databases
Semantic search in databasesSemantic search in databases
Semantic search in databases
 
Database Analysis
Database AnalysisDatabase Analysis
Database Analysis
 
MongoDB World 2016 : Advanced Aggregation
MongoDB World 2016 : Advanced AggregationMongoDB World 2016 : Advanced Aggregation
MongoDB World 2016 : Advanced Aggregation
 
R, Scikit-Learn and Apache Spark ML - What difference does it make?
R, Scikit-Learn and Apache Spark ML - What difference does it make?R, Scikit-Learn and Apache Spark ML - What difference does it make?
R, Scikit-Learn and Apache Spark ML - What difference does it make?
 
Database Analysis
Database AnalysisDatabase Analysis
Database Analysis
 
Data Analytics Project Presentation
Data Analytics Project PresentationData Analytics Project Presentation
Data Analytics Project Presentation
 
YearQuarterLocationCarClassRevenue NumCars 2017Q1Downt.docx
YearQuarterLocationCarClassRevenue  NumCars  2017Q1Downt.docxYearQuarterLocationCarClassRevenue  NumCars  2017Q1Downt.docx
YearQuarterLocationCarClassRevenue NumCars 2017Q1Downt.docx
 
http://boxinglatestnews.com
http://boxinglatestnews.comhttp://boxinglatestnews.com
http://boxinglatestnews.com
 
Using machine learning to generate predictions based on the information extra...
Using machine learning to generate predictions based on the information extra...Using machine learning to generate predictions based on the information extra...
Using machine learning to generate predictions based on the information extra...
 
Predicting model for prices of used cars
Predicting model for prices of used carsPredicting model for prices of used cars
Predicting model for prices of used cars
 
CARVANA - Predicting the purchase quality in car
CARVANA - Predicting the  purchase quality in carCARVANA - Predicting the  purchase quality in car
CARVANA - Predicting the purchase quality in car
 
2003 DODGE RAM TRUCK Service Repair Manual
2003 DODGE RAM TRUCK Service Repair Manual2003 DODGE RAM TRUCK Service Repair Manual
2003 DODGE RAM TRUCK Service Repair Manual
 
2003 DODGE RAM TRUCK Service Repair Manual
2003 DODGE RAM TRUCK Service Repair Manual2003 DODGE RAM TRUCK Service Repair Manual
2003 DODGE RAM TRUCK Service Repair Manual
 
The select statement
The select statementThe select statement
The select statement
 
C# Programming Help
C# Programming HelpC# Programming Help
C# Programming Help
 
Patterns and practices for real-world event-driven microservices by Rachel Re...
Patterns and practices for real-world event-driven microservices by Rachel Re...Patterns and practices for real-world event-driven microservices by Rachel Re...
Patterns and practices for real-world event-driven microservices by Rachel Re...
 
Patterns and practices for real-world event-driven microservices
Patterns and practices for real-world event-driven microservicesPatterns and practices for real-world event-driven microservices
Patterns and practices for real-world event-driven microservices
 
mercedes benz training presentation
mercedes benz training presentationmercedes benz training presentation
mercedes benz training presentation
 
Software Engineer Screening Question - OOP
Software Engineer Screening Question - OOPSoftware Engineer Screening Question - OOP
Software Engineer Screening Question - OOP
 
Data Warehouse and OLAP - Lear-Fabini
Data Warehouse and OLAP - Lear-FabiniData Warehouse and OLAP - Lear-Fabini
Data Warehouse and OLAP - Lear-Fabini
 

Mais de Forrester High School (20)

Program Design
Program DesignProgram Design
Program Design
 
Database Evaluation
Database EvaluationDatabase Evaluation
Database Evaluation
 
Data Dictionary
Data DictionaryData Dictionary
Data Dictionary
 
Compound Keys
Compound KeysCompound Keys
Compound Keys
 
Entity Occurrence Diagrams
Entity Occurrence DiagramsEntity Occurrence Diagrams
Entity Occurrence Diagrams
 
Entity Relationship Diagrams
Entity Relationship DiagramsEntity Relationship Diagrams
Entity Relationship Diagrams
 
Database Analysis
Database AnalysisDatabase Analysis
Database Analysis
 
Software Evaluation
Software EvaluationSoftware Evaluation
Software Evaluation
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
Standard Algorithms
Standard AlgorithmsStandard Algorithms
Standard Algorithms
 
File Handling
File HandlingFile Handling
File Handling
 
Python Predefined Functions
Python Predefined FunctionsPython Predefined Functions
Python Predefined Functions
 
Python Substrings
Python SubstringsPython Substrings
Python Substrings
 
Variable Scope
Variable ScopeVariable Scope
Variable Scope
 
Sub-programs
Sub-programsSub-programs
Sub-programs
 
Records in Python
Records in PythonRecords in Python
Records in Python
 
Parallel arrays in python
Parallel arrays in pythonParallel arrays in python
Parallel arrays in python
 
SDD Predefined Functions
SDD Predefined FunctionsSDD Predefined Functions
SDD Predefined Functions
 
SDD Cconditional Loops
SDD Cconditional LoopsSDD Cconditional Loops
SDD Cconditional Loops
 
SDD Fixed Loops
SDD Fixed LoopsSDD Fixed Loops
SDD Fixed Loops
 

Último

Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...KokoStevan
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfSanaAli374401
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.MateoGardella
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 

Último (20)

Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 

SQL

  • 2. CAR HIRE DATABASE EXAMPLE • The following SQL query examples will relate to a car hire database which consists of 4 tables: Customer Booking Car Depot places contain s is stored at
  • 3. CAR HIRE DATABASE EXAMPLE • The following SQL query examples will relate to a car hire database which consists of 4 tables: Customer customerID forename surname telephone houseNum postcode Booking bookingRef customerID * registration * daysBooked startDate Car registration make model colour depotID * automatic dailyPrice mileage Depot depotID depotName depotCity onlineBookin g depotHours employees
  • 4. WILDCARDS • A wildcard is a symbol used to replace or represent one or more characters. • SQL wildcards are used with the LIKE operator. • % wildcard – matches one or more characters • _ wildcard – matches exactly one character • (Note that Microsoft Access uses • * in place of %, • ? In place of _
  • 5. WILDCARDS EXAMPLE 1 • Write an SQL query to display the make, model and mileage of a car in a depot which is open all day, and where the make of car starts with ‘M’. SELECT make, model, mileage, depotName, depotHours FROM car, depot WHERE depotHours = 'All Day' and make LIKE ‘M%' AND car.depotID = depot.depotID;
  • 6. WILDCARDS EXAMPLE 1 • Write an SQL query to display the make, model and mileage of a car in a depot which is open all day, and where the make of car starts with ‘M’. make model mileag e depotName depotHours Mazda 3 19210 Summerville Street All Day Mercede s A- Class 30043 Summerville Street All Day Mazda 3 84662 Smith’s Garage All Day
  • 7. WILDCARDS EXAMPLE 2 • Write an SQL query to display a customer’s full name, booking ID, car make and model, and depot name for all customers who have ‘e’ as the 5th letter of their surname • List the details in alphabetical order of the customer surname SELECT forename, surname, bookingRef, make, model, depotName FROM customer, booking, car, depot WHERE surname LIKE ‘____e%' AND customer.customerID = booking.customerID AND booking.registration = car.registration AND car.depotID = depot.depotID ORDER BY surname;
  • 8. WILDCARDS EXAMPLE 2 • Write an SQL query to display a customer’s full name, booking ID, car make and model, and depot name for all customers who have ‘e’ as the 5th letter of their surname • List the details in alphabetical order of the customer surname forenam e surname bookingRe f make model depotName Leanne Docherty B3648 Volkswage n Polo Machine Works Mike Fraser B3658 Volkswage n Golf Castle Mike Fraser B3481 Volkswage n Golf Summerville Street Stephen Grimes B3660 Volkswage Golf Castle
  • 9. AVG • The AVG() function returns the average value of a numeric column. • Write an SQL query to display the average mileage of all the cars in the car table. SELECT AVG(mileage) FROM car;
  • 10. AVG avg 28950.95 • The AVG() function returns the average value of a numeric column. • Write an SQL query to display the average mileage of all the cars in the car table.
  • 11. MIN, MAX & ALIASES • The MIN() and MAX functions returns the largest and smallest values of a numeric column. • Aliases can be used to give columns a more readable name. The SQL AS statement does this. • Write an SQL query to display the lowest and highest mileages of the cars in the car table. The result should have a readable heading. SELECT MIN(mileage) AS [Lowest Mileage], MAX(mileage) AS [Highest Mileage] FROM car;
  • 12. MIN, MAX & ALIASES • The MIN() and MAX functions returns the largest and smallest values of a numeric column. • Aliases can be used to give columns a more readable name. The SQL AS statement does this. • Write an SQL query to display the lowest and highest mileages of the cars in the car table. The result should have a readable heading. Lowest Mileage Highest Mileage 6979 102300
  • 13. COUNT • The COUNT() function returns the number of rows that match a specified criteria. • Write an SQL query to display the cities that have depot, together with the number of depots in each city. SELECT depotCity, COUNT(*) FROM depot GROUP BY depotCity;
  • 14. depotCity count Edinburgh 3 Glasgow 2 Inverness 1 Perth 1 COUNT • The COUNT() function returns the number of rows that match a specified criteria. • Write an SQL query to display the cities that have depot, together with the number of depots in each city.
  • 15. SUM • The SUM() function returns the sum of a numeric column. • Write an SQL query to display the number of employees that are based in depots in Edinburgh or Glasgow. Use ‘Edinburgh/Glasgow Employees’ as a readable heading. SELECT SUM(employees) AS [Edinburgh/Glasgow Employees] FROM depot WHERE depotCity = 'Edinburgh' OR depotCity = 'Glasgow';
  • 16. SUM • The SUM() function returns the sum of a numeric column. • Write an SQL query to display the number of employees that are based in depots in Edinburgh or Glasgow. Use ‘Edinburgh/Glasgow Employees’ as a readable heading. Edinburgh/Glasgow Employees 36
  • 17. GROUP BY • The GROUP BY statement groups rows with the same values together. • Write an SQL query to display a list of each car colour, together with the number of bookings made for cars of those colours. • List the details from the least popular colour to the most popular colour. SELECT colour, COUNT(*) FROM car, booking WHERE booking.registration = car.registration GROUP BY colour ORDER BY COUNT(*) ASC;
  • 18. GROUP BY • The GROUP BY statement groups rows with the same values together. • Write an SQL query to display a list of each car colour, together with the number of bookings made for cars of those colours. • List the details from the least popular colour to the most popular colour. colour count Blue 1 Red 2 Black 4 Sliver 5 White 6
  • 19. UPDATE • The UDPATE command can be used to update the values of more than one field. • The details of the car with registration BA18 HER have changed, use SQL to update the car record as follows: • mileage = 21540 • dailyPrice = 38 UPDATE car SET mileage = 21540, dailyPrice = 38 WHERE registration = 'BA18 HER';
  • 20. UPDATE • The UDPATE command can be used to update the values of more than one field. • The details of the car with registration BA18 HER have changed, use SQL to update the car record as follows: • mileage = 21540 • dailyPrice = £38.00 registratio n make model colour depotID automati c dailyPric e mileage BA18 HER Volkswage n Golf Black D1004  £40.00 21233 registratio n make model colour depotID automati c dailyPric e mileage BA18 HER Volkswage n Golf Black D1004  £38.00 21540
  • 21. COMPUTED VALUES • A computed value is a calculation within a SELECT statement. • Write an SQL query to display the surname, booking reference, number of days booked, daily price, and a calculated total cost of each booking (with a readable column heading). • Display the most expensive booking first. SELECT surname, bookingRef, daysBooked, dailyPrice, daysBooked * dailyPrice AS [Total Cost] FROM customer, booking, car WHERE customer.customerID = booking.customerID AND booking.registration = car.registration ORDER BY daysBooked * dailyPrice DESC;
  • 22. COMPUTED VALUES • Write an SQL query to display the surname, booking reference, number of days booked, daily price, and a calculated total cost of each booking (with a readable column heading). • Display the most expensive booking first. surname bookingRe f daysBooke d dailyPric e Total Cost Grimes B3660 6 £42.00 £252.00 MacArthur B3655 7 £33.00 £231.00 Green B3524 5 £41.00 £205.00 Li B3578 4 £42.00 £168.00 Watson B3562 3 £52.00 £156.00 Fraser B3481 3 £38.00 £114.00 Gorecki B3537 1 £40.00 £40.00
  • 23. USING THE RESULT OF A QUERY • The result of a query can be used as a table in a second query. • Write an SQL query to display the name of depots that have cars with the cheapest daily price together with the price (use a readable heading to display the cheapest price). • This solution will require two separate queries: • Query 1: a simple query to generate a single value (the cheapest daily price) • Query 2: uses Query 1 to find the depots with the cheapest daily price
  • 24. USING THE RESULT OF A QUERY • Write an SQL query to display the name of depots that have cars with the cheapest daily price together with the price (use a readable heading to display the cheapest price). Query 1 – Find Minimum Daily Price SELECT MIN(dailyPrice) AS [Cheapest Daily Price] FROM car;
  • 25. USING THE RESULT OF A QUERY • Write an SQL query to display the name of depots that have cars with the cheapest daily price together with the price (use a readable heading to display the cheapest price). Query 1 – Find Minimum Daily Price Cheapest Daily Price £21.00
  • 26. USING THE RESULT OF A QUERY • Write an SQL query to display the name of depots that have cars with the cheapest daily price together with the price (use a readable heading to display the cheapest price). Query 2 – Display names of depots with cars at cheapest daily price SELECT depotName, [Cheapest Daily Price] FROM car, depot, [Find Minimum Daily Price] WHERE dailyPrice = [Cheapest Daily Price] AND car.depotID = depot.depotID;
  • 27. USING THE RESULT OF A QUERY • Write an SQL query to display the name of depots that have cars with the cheapest daily price together with the price (use a readable heading to display the cheapest price). Query 2 – Display names of depots with cars at cheapest daily price depotName Cheapest Daily Price Smith’s Garage £21.00 Green Place £21.00 Machine Works £21.00
  • 28. USING THE RESULT OF A QUERY Second Example: • Write an SQL query to display the details of any automatic car with a daily price that is above the average daily price. The query should display the car make, model, colour, automatic and daily price. • The most expensive cars should be listed first. • This solution requires two separate queries. • Query 1: a simple query to generate a single value (the average daily price) • Query 2: uses Query 1 to find the automatic cars that are above the average daily price
  • 29. USING THE RESULT OF A QUERY Second Example: • Write an SQL query to display the details of any automatic car with a daily price that is above the average daily price. The query should display the car make, model, colour, automatic and daily price. The most expensive cars should be listed first. Query 1 – Find Average Daily Price SELECT AVG(dailyPrice) AS [Average Daily Price] FROM car;
  • 30. USING THE RESULT OF A QUERY Second Example: • Write an SQL query to display the details of any automatic car with a daily price that is above the average daily price. The query should display the car make, model, colour, automatic and daily price. The most expensive cars should be listed first. Query 1 – Find Average Daily Price Average Daily Price £34.68
  • 31. USING THE RESULT OF A QUERY Second Example: • Write an SQL query to display the details of any automatic car with a daily price that is above the average daily price. The query should display the car make, model, colour, automatic and daily price. The most expensive cars should be listed first. Query 2 – Display automatic cars with daily price above average daily price SELECT make, model, colour, automatic, dailyPrice, [Average Daily Price] FROM car, [Find Average Daily Price] WHERE dailyPrice > [Average Daily Price] AND automatic = TRUE
  • 32. USING THE RESULT OF A QUERY Second Example: • Write an SQL query to display the details of any automatic car with a daily price that is above the average daily price. The query should display the car make, model, colour, automatic and daily price. The most expensive cars should be listed first. Query 2 – Display automatic cars with daily price above average daily price make model colour automati c dailyPric e Average Daily Price Mercedes A-Class Red  £52.00 £34.68 Nissan Qashqa i Silver  £46.00 £34.68 Volkswage Golf Black  £37.00 £34.68