Lesson 6 - SQL SELECT II
Lesson 6 - SQL SELECT II
■ The ORDER BY clause in SQL is used to sort the result set in ascending
or descending order.
■ Example
-- orders all rows from Customers in ascending order by country
SELECT *
FROM Customers
ORDER BY country;
■ The SQL command selects all rows from the Customers table and then
sorts them in ascending order by country.
SQL ORDER BY Syntax
■ column1, column2, ... are the columns to be included in the result set
■ table is the name of the table from where the rows are selected
■ columnA, columnB, ... are the column(s) based on which the rows will
be ordered
SQL ORDER BY Syntax
ORDER BY ASC (Ascending
Order)
■ We can use the ASC keyword to explicitly sort selected records
in ascending order. For example,
■ The SQL command selects all the rows from Customers table and then
sorts them in ascending order by age.
ORDER BY ASC (Ascending
Order)
ORDER BY DESC (Descending
Order)
-- sort all rows from Customers, first by first_name and then by age
SELECT *
FROM Customers
ORDER BY first_name, age;
■ The SQL command selects all the records and then sorts them by
first_name. If the first_name repeats more than once, it sorts those
records by age.
ORDER BY With Multiple Columns
ORDER BY With WHERE
We can also use ORDER BY with the SELECT WHERE clause. For example,
-- select last_name and age of customers who don't live in the UK
-- and sort them by last_name in descending order
■ In SQL, we use the GROUP BY clause to group rows based on the value
of columns.
■ Example
-- count the number of orders of each item
SELECT COUNT(order_id), item
FROM Orders
GROUP BY item;
SQL GROUP BY Syntax
■ In SQL, we use the GROUP BY clause to group rows based on the value of
columns.
■ Example
SELECT column1, column2, ...
FROM table GROUP BY columnA, columnB, ...;
■ The SQL command groups the rows by the country column and counts
the number of each country (because of the COUNT() function).
Example: GROUP BY Number of
Customers in Each Country
Example: GROUP BY Amount
Spent By Each Customer
-- calculate the total amount spent by each customer
SELECT customer_id, SUM(amount) AS total
FROM Orders
GROUP BY customer_id;
We can also use the GROUP BY clause with the JOIN clause. For
example,
-- join the Customers and Orders tables
-- select customer_id and first_name from Customers table
-- also select the count of order ids from Orders table
-- group the result by customer_id
The SQL command joins the Customers and Orders tables and groups
the result set by customer_id (a customer).
SQL LIKE and NOT LIKE
Operators
We use the SQL LIKE operator with the WHERE clause to get a result
set that matches the given string pattern.
Example
We can also invert the working of the LIKE operator by using the NOT operator
with it. This returns a result set that doesn't match the given string pattern.
For example,
-- select customers who don't live in the USA
SELECT *
FROM Customers
WHERE country NOT LIKE 'USA';
■ The SQL command selects all customers except those whose country
is USA.
SQL LIKE With Multiple Values
For example,
■ We can use the LIKE operator with multiple string patterns using the OR
operator. For example,
-- select customers whose last_name starts with R and ends with t
-- or customers whose last_name ends with e
SELECT *
FROM Customers
WHERE last_name LIKE 'R%t' OR last_name LIKE '%e';
■ The SQL command selects customers whose last_name starts with R
and ends with t or customers whose last_name ends with e.
SQL Wildcards
A wildcard character in SQL is used with the LIKE clause to replace a single
character or a set of characters in a string.% and _ are two commonly used
wildcard characters in SQL.
Example
-- select customers who live in countries -- that start with 'US' followed by a single
character
SELECT *
FROM Customers
WHERE country LIKE 'US_'
_ is a wildcard character that represents exactly one character after a string.
So, the SQL query selects customers whose country starts with US and ends
with a single character after it.
SQL Wildcard Syntax
column1, column2, ... are the columns to select the data from
table is the name of the table
column is the column we want to apply the filter to
LIKE matches the column with Wildcard String
Wildcard String is a combination of strings and wildcard characters
SQL Wildcard Syntax
For example,
-- select rows where the last name -- of customers start with R
SELECT *
FROM Customers
WHERE last_name LIKE 'R%';
U_ UK match
USA no match
[] Wildcard in SQL
The [] wildcard in SQL is used to represent any one character inside
brackets.
select
-- For example,
customers with country that starts with UK or UA -- and is followed by any
number of characters
SELECT *
FROM Customers
WHERE country LIKE 'U[KA]%';
The SQL command selects customers whose country name starts with
U and isExpression
followed by either String
K or A and any number of characters
Matched?
afterward.
U no match
UK match
U[KA]%
UAE match
USA no match
! Wildcard in SQL
The ! wildcard in SQL is used to exclude characters from a string. For
example,
--select rows where customer's last names don't start with D or R
SELECT *
FROM Customers
WHERE last_name LIKE '[!DR]%';
The SQL command selects customers whose last_name does not start
Expression String Matched?
with D or R.
Doe no match
Reinhardt no match
Luna match
[!DR]%
D no match
O match
R no match
SQL UNION
The UNION operator selects fields from two or more tables.
-- select the union of name columns from two tables Teachers and Students
SELECT name
FROM Teachers
UNION
SELECT name
FROM Students;
The SQL command selects the union of the name columns from two
different tables: Teachers and Students.
SQL Union Syntax
SELECT column1, column2, ...
FROM table1
UNION
SELECT column1, column2, ...
FROM table2;
column1,column2, ... are the column names required for the union
table1 and table2 are the names of the tables to fetch the columns from
UNION combines the columns in the tables
Example: SQL UNION
-- select the union of age columns from two tables Teachers and Students
SELECT age
FROM Teachers
UNION
SELECT age
FROM Students;
The SQL command returns the age columns from the Teachers and
the Students tables, ignoring the duplicate fields.
Example: SQL UNION
Example: SQL UNION With WHERE Clause
-- select the union of age columns from both Teachers and Students tables where age >=
20
SELECT age, name FROM Teachers
WHERE age >= 20
UNION
SELECT age, name FROM Students
WHERE age >= 20;
The SQL command selects the age column (only the unique values)
from both tables where the age is greater than or equal to 20.
SQL UNION ALL Operator
The UNION ALL operator selects fields from two or more tables similar
to UNION. However, unlike UNION, UNION ALL doesn't ignore duplicate fields.
Let's try the previous SQL command again using UNION ALL instead of UNION.
The SQL command selects the age column from both tables (including
duplicate values) where the age is greater than or equal to 20.
SQL Subquery
In SQL, a SELECT statement may contain another SQL statement, known
as a subquery or nested query. Example,
-- use a subquery to select the first name of customer -- with the highest age
SELECT first_name
FROM Customers
WHERE age= (
-- subquery
SELECT MAX(age)
FROM CUSTOMERS );
■ Now to select the customers who lives in USA, we can simply run,
SELECT * FROM us_customers;
Updating a View
■ It's possible to change or update an existing view using the CREATE OR
REPLACE VIEW command.
■ For example,
CREATE OR REPLACE VIEW us_customers AS
SELECT *
FROM Customers
WHERE Country = 'USA';
We can delete views using the DROP VIEW command. For example,
SELECT *
FROM order_details;
The CTE PendingShippings selects all shippings whose status value is Pending.
The UPDATE statement then updates these shippings to In Transit.
SQL ANY AND ALL
SQL ANY Operator
SQL ANY compares a value of the first table with all values of the second table and
returns the row if there is a match with any value.
It has the following syntax:
SELECT column
FROM table1
WHERE column OPERATOR ANY (
SELECT column
FROM table2 );
Here, the subquery returns all the ages from the Students table.
SELECT age FROM Students
And, the condition below compares the student ages (returned by
subquery) with the ages of the teachers.
WHERE age = ANY (...)
We can use any comparison operators like =, >, <, etc., with the ANY and
ALL keywords.
Let's look at an example where we want teachers whose age is less than
any* student.
SELECT
FROM Teachers
WHERE age < ANY (
SELECT age
FROM Students );
The SQL command selects rows if age in the outer query is less than any
age in a subquery.
Example 2: SQL ANY With the < Operator
SQL ALL Operator
SQL ALL compares a value of the first table with all values of the second
table and returns the row if there is a match with all values.
SELECT column
FROM table1
WHERE column OPERATOR ALL (
SELECT column
FROM table2 );
Here,
SELECT agethe subquery
FROM Studentsbelow returns all the ages from the Students table.
And, the condition below compares the student ages (returned by subquery)
with
WHERE the
age ages
> ALL (...)of the teachers.
If the teacher's age is greater than all student's ages, the corresponding row of
the Teachers table is selected.
Example 3: SQL ALL Operator
SQL CASE
The SQL CASE statement evaluates a list of conditions and adds a column
with values based on the condition. For example,
The result set has a new column, order_volume which labels the rows with
amounts greater than or equal to 10000 as Large Order and smaller than
10000 as Small Order.
SQL CASE Syntax
SELECT column1, column2,... ,
CASE
WHEN condition THEN result END AS alias_name
FROM table;
The SQL command checks each row with the given case. The result set
contains:
values from customer_id and first_name columns
a new can_vote column with value Allowed if age is greater than 18,
otherwises empty
Example: Voter Eligibility Using SQL CASE
Example: SQL CASE to Calculate the
Discount Amount
Let's take a look at another example where we want to provide a 10%
discount on each order for a Christmas sale if the amount is 400 or
more.
SELECT order_id, customer_id,
CASE
WHEN amount >= 400 THEN (amount - amount * 10/100)
END AS offer_price
FROM Orders;
The CASE statement checks if the amount is greater than or equal to 400. If
this condition is satisfied, a new column offer_price will contain the values
equal to amount - amount * 10/100.
CASE With Multiple Conditions
It is also possible to stack multiple conditions inside a single CASE clause.
SELECT column1, column2, ...
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
-- Add more WHEN conditions and results as needed
END AS alias_name
FROM table_name;
We can add as many WHEN ... THEN conditions as required in
the CASE statement. For example,
-- multiple CASE conditions in SQL
SELECT customer_id, first_name,
CASE
WHEN country = 'USA' THEN 'United States of America’
WHEN country = 'UK' THEN 'United Kingdom’
END AS country_name
FROM Customers;
CASE With Multiple Conditions
-- multiple CASE conditions in SQL
SELECT customer_id, first_name,
CASE
WHEN country = 'USA' THEN 'United States of America’
WHEN country = 'UK' THEN 'United Kingdom’
END AS country_name
FROM Customers;
checks for the order_id of customers in the Orders table where amount is less
than 12000
returns the customer_id and first_name of customers from the Customers table
who have made a purchase of less than 12000
SQL Exists Syntax
The SQL command returns a row from the Customers table if the related
row is not in the Orders table.