SQL
SQL is a standard language for accessing databases.
SQL stands for Structured Query Language.
Using SQL you can
execute queries against a database
retrieve data from a database
insert, update and delete records in a database
SQL can create new databases and tables
SQL SELECT
SELECT Forename, Surname FROM Students;
SQL SELECT
SELECT Forename, Surname FROM Students;
SQL SELECT
SELECT Forename, Surname FROM Students
WHERE TutorGroup = ‘2T1’;
SQL SELECT
SELECT Forename, Surname FROM Students
WHERE TutorGroup = ‘2T1’;
SQL SELECT – OR
SELECT Forename, Surname FROM Students
WHERE TutorGroup = ‘3R1’
OR TutorGroup = ‘3R2’;
SQL SELECT – OR
SELECT Forename, Surname FROM Students
WHERE TutorGroup = ‘3R1’
OR TutorGroup = ‘3R2’;
SQL SELECT – AND
SELECT Forename, Surname FROM Students
WHERE Forename = ‘Stephen’
AND TutorGroup = ‘3R1’;
SQL SELECT – AND
SELECT Forename, Surname FROM Students
WHERE Forename = ‘Stephen’
AND TutorGroup = ‘3R1’;
SQL SELECT *
SELECT * FROM Students
WHERE Surname = ‘French’;
SQL SELECT *
SELECT * FROM Students
WHERE Surname = ‘French’;
SQL SELECT – COMPARISONS
Can use >, <, = comparison operators:
SELECT * FROM Students
WHERE Age >= 14 and Age <=17;
Can also use BETWEEN:
SELECT * FROM Students
WHERE Surname BETWEEN ‘Langley’ AND ‘Jones’;
SQL SELECT ORDER BY
SELECT Forename, Surname FROM Students
ORDER BY Surname;
SQL SELECT ORDER BY
SELECT Forename, Surname FROM Students
ORDER BY Surname;
SQL SELECT ORDER BY DESC
SELECT Forename, Surname FROM Students
ORDER BY Surname DESC;
SQL SELECT ORDER BY DESC
SELECT Forename, Surname FROM Students
ORDER BY Surname DESC;
SQL INSERT INTO
INSERT INTO Students (CandidateNumber, Forename, Surname, DOB,
TutorGroup)
VALUES (07551881’, ‘Aisha’, ‘Obeke’, ‘08/03/01’, 2T2’);
SQL INSERT INTO
INSERT INTO Students (CandidateNumber, Forename, Surname, DOB,
TutorGroup)
VALUES (07551881’, ‘Aisha’, ‘Obeke’, ‘08/03/01’, 2T2’);
SQL UPDATE
UPDATE Students
SET TutorGroup TO ‘2T2’
WHERE CandidateNumber = ‘07541120’;
SQL UPDATE
UPDATE Students
SET TutorGroup TO ‘2T2’
WHERE CandidateNumber = ‘07541120’;
SQL DELETE
DELETE FROM Students
WHERE CandidateNumber = ‘07743612’;
SQL DELETE
DELETE FROM Students
WHERE CandidateNumber = ‘07743612’;
Wildcards
A wildcard character is used to replace one or more
characters in a string.
Wildcards are useful in situations when incomplete
information is available.
A LIKE operator is used with a wildcard.
Two different wildcards that can be used:
% (the percent symbol) is used to represent zero, one
or multiple characters.
_ (the underscore symbol) is used to represent a single
character.
(Access uses an astrisk (*) rather than a % and a question
mark (?) rather than _)
Wildcard examples
Example Purpose
WHERE surname LIKE ‘Thom%’ Used to find any values in the surname
field that start with “Thom”
WHERE surname LIKE ‘%son’ Used to find any values in the surname
field that end with “son”
WHERE surname LIKE ‘%is%’ Used to find any values that have “is”
anywhere in the surname field.
WHERE surname LIKE ‘_h%’ Used to find any values in the surname
field that have “h” as the second
character.
WHERE surname LIKE ‘m % %’ Used to find any vlues in the surname
field that start with “m” and have at
least 3 characters.
WHERE surname LIKE ‘a%Z’ Used to find any values in the surname
field that start with “a” and end with
“z”.
Wildcard example
Example 1
Used to search the database to display the name,
swimming pool details, resort and resort type of any
hotel in a coastal resort that starts with the letter ‘A’.
SELECT hotelName, swimmingPool, resortName, resortType
FROM Hotel, Resort
WHERE Hotel.resortID = Resort.resortID AND resortName
LIKE ‘A*’ AND resortType = ‘coastal’;
Wildcard example
Example 2
Used to display the customer’s full name, booking number, start date,
hotel name and resort name of all customers who has an ‘h’ as the
second letter of their surname. These details should be listed in
alphabetical orger of surname: customers within the same surname
should be listed so that the customer with the earliest holiday should be
listed first.
SELECT firstname, surname, bookingNo, hotelName, resortName,
startDate
FROM Customer, Booking, Hotel, Resort
WHERE Customer.[customer#]=Booking.[customer#] AND
Booking.hotelRef=Hotel.hotelRef AND Hotel.resortID=Resort.resortID
AND surname LIKE ‘?h*’
ORDER BY surname ASC, startDate ASC;
Wildcards
SELECT Forename, Surname FROM Students
WHERE TutorGroup LIKE= ‘3%’;
Wildcards
SELECT Forename, Surname FROM Students
WHERE TutorGroup LIKE= ‘3%’;
Wildcards
SELECT Forename, Surname FROM Students
WHERE TutorGroup LIKE= ‘%T%’;
Wildcards
SELECT Forename, Surname FROM Students
WHERE TutorGroup LIKE= ‘%T%’;
SQL INNER JOIN
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID
Two tables, Orders and Customers
Customer.CustomerID is PK in Customers table
Orders.CustomerID is FK in Orders table
SQL INNER JOIN
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID
Aggregate Functions
Aggregate functions operate on a set of rows to return
a single, statistical value. You apply an aggregate to a
set of rows, which may be:
All the rows in a table
Only those rows specified by a WHERE clause
Those rows created by a GROUP BY clause (see later)
Aggregate Functions
Function Description
AVG ( ) Returns the average value of a numeric column or
expression
COUNT ( ) Returns the number rows that match the criteria in the
WHERE clause.
MAX ( ) Returns the largest value of the selected column or
expression
MIN ( ) Returns the smallest value of the selected column or
expression.
SUM ( ) Returns the total sum of a numeric column or expressions.
The most common aggregate functions used are listed below:
Examples
Uses readable headings to display the cheapest and
dearest price per night.
Used to display the average number of nights booked.
SELECT MIN(pricePersonNight) AS [Cheapest Price per Night],
MAX(pricePersonNight) AS [Dearest Price perNight]
FROM Hotel;
SELECT ROUND(AVG(numberNights),2)
FROM Booking;
Examples
Used to display a list of the different types of resort
together with the number of resorts in each of those
categories.
Uses a readable heading to display the total number
of people booked into a hotel in July.
SELECT resortType, COUNT (*)
FROM Resort
GROUP BY resortType;
SELECT SUM(numberInParty) AS [People on holiday in July]
FROM Booking
WHERE startDate LIKE ‘*/07/*’;
Arithmetic Expressions
Arithmetic expressions can be used to compute
values as part of a SELECT query. The arithmetic
expressions can contain column names, numeric
numbers and arithmetic operators.
An Alias can be used to give any column in an answer
table a temporary name.
Examples
The query below will display the name, price,
quantity and cost of each product in a specified order.
Executing the query produces the answer table below:
SELECT productName AS ['Product Name'], price,
quantity, price*quantity
FROM Product, Order
WHERE Product.productID = [Order].productID AND order#
- 123456;
We can make the table more readable by using an
alias:
Executing the query produces the answer table below:
SELECT productName AS ['Product Name'], price,
quantity, price*quantity AS ['Product Cost']
FROM Product, Order
WHERE Product.productID = [Order].productID AND order#
= 123456;
Group by
The GROUP BY clause is used in a SELECT to form
sets (or goups) of records. It does this by gathering
together all the records that have identical data in the
specified column.
Example
The query below is used to display a list of products
categories together with the dearest product in each
of those categories. The category with the cheapest
product is listed first.
Example
Use to display the number of bookings for hotels in
coastal resorts. Show the resort type and use a
readable heading for the results returned by the
aggregate function.
Example
Use to display a list of each type of meal plan together
with the number of bookings made for each of those
meal plans. The details should be listed from the least
popular meal plan to the most popular.

Higher SQL

  • 2.
    SQL SQL is astandard language for accessing databases. SQL stands for Structured Query Language. Using SQL you can execute queries against a database retrieve data from a database insert, update and delete records in a database SQL can create new databases and tables
  • 3.
    SQL SELECT SELECT Forename,Surname FROM Students;
  • 4.
    SQL SELECT SELECT Forename,Surname FROM Students;
  • 5.
    SQL SELECT SELECT Forename,Surname FROM Students WHERE TutorGroup = ‘2T1’;
  • 6.
    SQL SELECT SELECT Forename,Surname FROM Students WHERE TutorGroup = ‘2T1’;
  • 7.
    SQL SELECT –OR SELECT Forename, Surname FROM Students WHERE TutorGroup = ‘3R1’ OR TutorGroup = ‘3R2’;
  • 8.
    SQL SELECT –OR SELECT Forename, Surname FROM Students WHERE TutorGroup = ‘3R1’ OR TutorGroup = ‘3R2’;
  • 9.
    SQL SELECT –AND SELECT Forename, Surname FROM Students WHERE Forename = ‘Stephen’ AND TutorGroup = ‘3R1’;
  • 10.
    SQL SELECT –AND SELECT Forename, Surname FROM Students WHERE Forename = ‘Stephen’ AND TutorGroup = ‘3R1’;
  • 11.
    SQL SELECT * SELECT* FROM Students WHERE Surname = ‘French’;
  • 12.
    SQL SELECT * SELECT* FROM Students WHERE Surname = ‘French’;
  • 13.
    SQL SELECT –COMPARISONS Can use >, <, = comparison operators: SELECT * FROM Students WHERE Age >= 14 and Age <=17; Can also use BETWEEN: SELECT * FROM Students WHERE Surname BETWEEN ‘Langley’ AND ‘Jones’;
  • 14.
    SQL SELECT ORDERBY SELECT Forename, Surname FROM Students ORDER BY Surname;
  • 15.
    SQL SELECT ORDERBY SELECT Forename, Surname FROM Students ORDER BY Surname;
  • 16.
    SQL SELECT ORDERBY DESC SELECT Forename, Surname FROM Students ORDER BY Surname DESC;
  • 17.
    SQL SELECT ORDERBY DESC SELECT Forename, Surname FROM Students ORDER BY Surname DESC;
  • 18.
    SQL INSERT INTO INSERTINTO Students (CandidateNumber, Forename, Surname, DOB, TutorGroup) VALUES (07551881’, ‘Aisha’, ‘Obeke’, ‘08/03/01’, 2T2’);
  • 19.
    SQL INSERT INTO INSERTINTO Students (CandidateNumber, Forename, Surname, DOB, TutorGroup) VALUES (07551881’, ‘Aisha’, ‘Obeke’, ‘08/03/01’, 2T2’);
  • 20.
    SQL UPDATE UPDATE Students SETTutorGroup TO ‘2T2’ WHERE CandidateNumber = ‘07541120’;
  • 21.
    SQL UPDATE UPDATE Students SETTutorGroup TO ‘2T2’ WHERE CandidateNumber = ‘07541120’;
  • 22.
    SQL DELETE DELETE FROMStudents WHERE CandidateNumber = ‘07743612’;
  • 23.
    SQL DELETE DELETE FROMStudents WHERE CandidateNumber = ‘07743612’;
  • 24.
    Wildcards A wildcard characteris used to replace one or more characters in a string. Wildcards are useful in situations when incomplete information is available. A LIKE operator is used with a wildcard. Two different wildcards that can be used: % (the percent symbol) is used to represent zero, one or multiple characters. _ (the underscore symbol) is used to represent a single character. (Access uses an astrisk (*) rather than a % and a question mark (?) rather than _)
  • 25.
    Wildcard examples Example Purpose WHEREsurname LIKE ‘Thom%’ Used to find any values in the surname field that start with “Thom” WHERE surname LIKE ‘%son’ Used to find any values in the surname field that end with “son” WHERE surname LIKE ‘%is%’ Used to find any values that have “is” anywhere in the surname field. WHERE surname LIKE ‘_h%’ Used to find any values in the surname field that have “h” as the second character. WHERE surname LIKE ‘m % %’ Used to find any vlues in the surname field that start with “m” and have at least 3 characters. WHERE surname LIKE ‘a%Z’ Used to find any values in the surname field that start with “a” and end with “z”.
  • 26.
    Wildcard example Example 1 Usedto search the database to display the name, swimming pool details, resort and resort type of any hotel in a coastal resort that starts with the letter ‘A’. SELECT hotelName, swimmingPool, resortName, resortType FROM Hotel, Resort WHERE Hotel.resortID = Resort.resortID AND resortName LIKE ‘A*’ AND resortType = ‘coastal’;
  • 27.
    Wildcard example Example 2 Usedto display the customer’s full name, booking number, start date, hotel name and resort name of all customers who has an ‘h’ as the second letter of their surname. These details should be listed in alphabetical orger of surname: customers within the same surname should be listed so that the customer with the earliest holiday should be listed first. SELECT firstname, surname, bookingNo, hotelName, resortName, startDate FROM Customer, Booking, Hotel, Resort WHERE Customer.[customer#]=Booking.[customer#] AND Booking.hotelRef=Hotel.hotelRef AND Hotel.resortID=Resort.resortID AND surname LIKE ‘?h*’ ORDER BY surname ASC, startDate ASC;
  • 28.
    Wildcards SELECT Forename, SurnameFROM Students WHERE TutorGroup LIKE= ‘3%’;
  • 29.
    Wildcards SELECT Forename, SurnameFROM Students WHERE TutorGroup LIKE= ‘3%’;
  • 30.
    Wildcards SELECT Forename, SurnameFROM Students WHERE TutorGroup LIKE= ‘%T%’;
  • 31.
    Wildcards SELECT Forename, SurnameFROM Students WHERE TutorGroup LIKE= ‘%T%’;
  • 32.
    SQL INNER JOIN SELECTOrders.OrderID, Customers.CustomerName FROM Orders INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID Two tables, Orders and Customers Customer.CustomerID is PK in Customers table Orders.CustomerID is FK in Orders table
  • 33.
    SQL INNER JOIN SELECTOrders.OrderID, Customers.CustomerName FROM Orders INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID
  • 34.
    Aggregate Functions Aggregate functionsoperate on a set of rows to return a single, statistical value. You apply an aggregate to a set of rows, which may be: All the rows in a table Only those rows specified by a WHERE clause Those rows created by a GROUP BY clause (see later)
  • 35.
    Aggregate Functions Function Description AVG( ) Returns the average value of a numeric column or expression COUNT ( ) Returns the number rows that match the criteria in the WHERE clause. MAX ( ) Returns the largest value of the selected column or expression MIN ( ) Returns the smallest value of the selected column or expression. SUM ( ) Returns the total sum of a numeric column or expressions. The most common aggregate functions used are listed below:
  • 36.
    Examples Uses readable headingsto display the cheapest and dearest price per night. Used to display the average number of nights booked. SELECT MIN(pricePersonNight) AS [Cheapest Price per Night], MAX(pricePersonNight) AS [Dearest Price perNight] FROM Hotel; SELECT ROUND(AVG(numberNights),2) FROM Booking;
  • 37.
    Examples Used to displaya list of the different types of resort together with the number of resorts in each of those categories. Uses a readable heading to display the total number of people booked into a hotel in July. SELECT resortType, COUNT (*) FROM Resort GROUP BY resortType; SELECT SUM(numberInParty) AS [People on holiday in July] FROM Booking WHERE startDate LIKE ‘*/07/*’;
  • 38.
    Arithmetic Expressions Arithmetic expressionscan be used to compute values as part of a SELECT query. The arithmetic expressions can contain column names, numeric numbers and arithmetic operators. An Alias can be used to give any column in an answer table a temporary name.
  • 39.
    Examples The query belowwill display the name, price, quantity and cost of each product in a specified order. Executing the query produces the answer table below: SELECT productName AS ['Product Name'], price, quantity, price*quantity FROM Product, Order WHERE Product.productID = [Order].productID AND order# - 123456;
  • 40.
    We can makethe table more readable by using an alias: Executing the query produces the answer table below: SELECT productName AS ['Product Name'], price, quantity, price*quantity AS ['Product Cost'] FROM Product, Order WHERE Product.productID = [Order].productID AND order# = 123456;
  • 41.
    Group by The GROUPBY clause is used in a SELECT to form sets (or goups) of records. It does this by gathering together all the records that have identical data in the specified column.
  • 42.
    Example The query belowis used to display a list of products categories together with the dearest product in each of those categories. The category with the cheapest product is listed first.
  • 43.
    Example Use to displaythe number of bookings for hotels in coastal resorts. Show the resort type and use a readable heading for the results returned by the aggregate function.
  • 44.
    Example Use to displaya list of each type of meal plan together with the number of bookings made for each of those meal plans. The details should be listed from the least popular meal plan to the most popular.