You are on page 1of 25

Upcoming

• Quiz 3 on 10/4 (next week)

1
Creating ad hoc columns
• We can create temporary new columns based on the
values of existing columns. Name new columns with
the “AS” keyword, for example:

SELECT Salary + Raise AS New_Salary


FROM Employees;

2
Creating ad hoc columns
• We can also combine text-based columns using
CONCAT(), short for “concatenate,” for example:

SELECT CONCAT(First_Name, “ “, Last_Name) AS Full_Name


FROM Persons;

3
Sorting selections
• By default, SQL will return rows in an arbitrary order,
which is not necessarily significant

• We can sort by adding an ORDER BY clause after the


WHERE clause, for example:

SELECT First_Name, Last_Name Default sort is in


ascending order
FROM Employees
WHERE Job = “Analyst” To sort in ascending
order, either specify
ORDER BY Salary DESC; ASC or leave the sort
direction blank
4
Sorting selections
• We can also sort by multiple fields if desired. For
example, we could sort by salary first, and if two
employees have the same salary, then order those
employees by last name

SELECT First_Name, Last_Name Sort by salary


first, then sort by
FROM Employees last name if
salaries are tied
WHERE Job = “Analyst”
ORDER BY Salary DESC, Last_Name ASC;

5
SELECT examples
• Write queries to:

a) Select all fields from the foods table and add a


new field for the price plus the price increase.
Sort by that new value in descending order
b) Select a new field for employee full name (first
name and last name) as well as department code.
Sort by department code ascending, then last
name ascending

6 Week 6 Example 1 workplace.sql


Selecting distinct values
• Sometimes, we may want to see all the records
returned with no repeats
• Note that every record must be unique, but if we’re only
selecting some columns, then that combination may not be
unique

• For example, we could select all the unique


combinations of course title and instructor:
SELECT DISTINCT Course_Title, Instructor
FROM Classes
7 ORDER BY Course_Title ASC
Selecting partial text matches
• We can do exact text matches with “=”, but we can do
either partial or exact matches with LIKE. This is case-
insensitive
• WHERE Name = “Smith” Exact search
• WHERE Name LIKE “Smith” Exact search

• WHERE Name LIKE “S%” Starts with “S”


• WHERE Name LIKE “%ith” Ends with “ith” The % will match
• WHERE Name LIKE “%S%” Contains “S” any number of
characters

• WHERE Name LIKE “T_m” Middle character is variable


The _ will match
8 exactly one character
SELECT examples
• Write queries to:

a) Create a list of manager IDs without duplicates


b) List the first and last names of all employees
whose department code starts with “S”
c) List the first and last names of all employees
whose last names are five letters and end in “s”

9 Week 6 Example 2 workplace.sql


Dealing with null values
• Our queries can recognize and refer to possible null values

• We can filter where a value is null


SELECT * Select data for all
FROM Persons people with no listed
phone number
WHERE Phone IS NULL;

• Or we can filter where a value is not null


SELECT Course_Title Select data for all
FROM CLASSES classes that are
assigned an instructor
10 WHERE Instructor_ID IS NOT NULL;
SELECT examples
• Write queries to:

a) List the first name, last name, and manager ID for


all employees who do not have a manager
b) List the first name, last name, and manager ID for
all employees who do have a manager

11 Week 6 Example 3 workplace.sql


Aggregation
• Sometimes we might want to answer a high-level
question across many rows. For example, how many
employees do we have in total?

• Aggregate functions allow us to create totals for a


given table. For example, COUNT() will count the
number of rows:
The default name
for this
temporary
SELECT COUNT(*) AS Num_Players column is
FROM Players; “count(*)” unless
we specify one
12
Aggregation
• COUNT() can give us some different values depending on
what we count:
• COUNT(*) counts the number of rows in a table
• COUNT(column) counts the number of non-null values in a
column

• We might get different answers for:


SELECT COUNT(*) AS Num_Players
FROM Players; All players count

SELECT COUNT(Position) AS Num_Players


13
FROM Players; Players with null
positions wouldn’t count
Aggregation
• Other aggregate functions:
• MIN() Returns the minimum of a column
• MAX() Returns the maximum of a column
• SUM() Returns the sum of a column
• AVG() Returns the average of a column
• STD() Returns the standard deviation of a column
• VARIANCE() Returns the variance of a column

14
Aggregation examples
• Write queries to:

a) Count the total number of employees


b) Count the total number of managers
c) Calculate the average price of foods supplied by
supplier ID “Cbc”

15 Week 6 Example 4 workplace.sql


Aggregation
• In more advanced problems, we can use aggregation
to calculate sub-totals. After the WHERE clause but
before any ORDER BY clause, we can add a GROUP BY
clause to indicate which field(s) to use for subtotals

• For example, maybe we want to know the average


salary for each basketball position:
SELECT AVG(Salary), Position
FROM Players
GROUP BY Position
ORDER BY Position ASC
16
Aggregation examples
• Write queries to:

a) For each department code, list the number of


employees (as a count) and the total credit limit
(combined)
b) For each combination of department code and
manager ID, list the number of employees
supervised in descending order

17 Week 6 Example 5 workplace.sql


Subqueries
• Sometimes, we may want to use the result of one
query as an input into another query

• For example, what if we are interested in a list of all


foods that cost a below-average price?
• Step 1: figure out the average price
• Step 2: find all foods whose price is lower than the average
computed in step 1

18
Subqueries
• We can write a subquery by using putting an inner SQL
query in parentheses within our expression. For
example:

SELECT Employee_Name
FROM Employees
WHERE Salary >
Order of
(SELECT AVG(Salary) operations: the
parentheses
FROM Employees); (subquery)
occurs first
19
Subqueries
• A subquery may involve a single value (like an average)
or a list of values (like all foods by a certain supplier)

• For lists of values, in addition to our regular operators


(e.g., mathematical comparisons), subqueries also
allow us to use:
• IN – check whether a certain value appears in the list

20
Subqueries – IN
• An IN subquery checks if a subquery contains a certain
value. For example:

SELECT Player_Name
FROM Players Finds all players
WHERE Team_ID IN whose teams are
in Los Angeles
(SELECT Team_ID
FROM Teams
WHERE Location = “Los Angeles”);

• *Note: IN subqueries are often doing the same thing


as joins, which we will talk about later
21
Subqueries examples
• Write queries to:

a) List the description and price for all food items


provided by “A Soup Place”
b) List the description and price for all foods whose
prices are above the average price (descending
order)

22 Week 6 Example 6 workplace.sql


Views
• Sometimes, we will have an inner query that is used in
a lot of different subqueries
• For example, maybe the average price of foods is an inner
query that is used in a lot of situations

• To simplify our code, we can create a view, which is a


virtual table constructed from other tables

• A view has no data of its own, but it obtains the result


of some query based on other tables
23
Views
Just like tables,
each view must
• To create a view: have its own
unique name

CREATE VIEW Avg_F_Salary AS


SELECT AVG(Salary)
FROM Players
WHERE Position = “F”

24
Subqueries examples
• Write queries to:

a) List all employees whose credit limit is greater


than the average credit limit of the sales
department (subquery)
b) Create a view for the average credit limit of the
sales department
c) Redo part (a) to utilize the view

25 Week 6 Example 7 workplace.sql

You might also like