CS 3200
SQL - Part 1
Mark Fontenot, PhD
Northeastern University
1
Setting the Stage…
SQL: Structured Query Language
3
* See the Standards Overview section of the SQL Wikipedia Article
Categories of SQL Commands
SQL vs. Relational Algebra
SQL vs. Relational Algebra
Relational Algebra | SQL |
Relation (Relation Instance) | Table |
Relation Schema | Table Schema |
Attribute | Attribute or Column |
Tuple | Row |
Primary Key | Primary Key |
Foreign Key | Foreign Key |
NorthWind DB Schema
7
It’s SQL Time:
The SELECT Statement
Aside: Generic Syntax Statements
Intro to SELECTs
10
SELECT FirstName
FROM Employees;
Intro to SELECTs
What this does: retrieves a table with attributes <col1>, <col2>, … from the identified table.
Note: I will capitalize keywords in SQL statements, but not strictly required by SQL.
11
SELECT <col1>[, <col2>, …]
FROM <table name>;
SELECT Specific
Columns
Returns a table containing the ProductID and ProductName columns from the Products table.
12
SELECT ProductID, ProductName
FROM Products;
UnitPrice
UnitsInStock
Retrieve All Columns
13
SELECT *
FROM Products;
UnitPrice
UnitsInStock
Renaming/Aliasing �Columns
14
SELECT ProductID AS p_id, � ProductName AS p_name
FROM Products;
SELECT <column> AS <newName>, …
FROM <table name>;
General�Form
Example
UnitPrice
UnitsInStock
Renaming/Aliasing �Columns
Returns a table with columns named p_id and p_name.
15
SELECT ProductID AS p_id, � ProductName AS p_name
FROM Products;
UnitPrice
UnitsInStock
Basic Calculations
16
SELECT OrderID, ProductID, � (UnitPrice * Quantity) AS cost
FROM OrderDetails;
UnitPrice
UnitsInStock
Sample Query 1
For all customers, provide a list containing the customer name, contact person’s name, their city, and postal code.
17
UnitPrice
UnitsInStock
Sample Query 2
Your boss sends you the following email… “Hi! Could you get me a list of all products with our current stock levels? Thanks!”
18
UnitPrice
UnitsInStock
Sample Query 3
The stockroom manager needs to know the current value of each product we currently have in stock. So, if we have 10 units of Sharp Cheddar, what is the total value for those 10 units. Can you help them?
19
UnitPrice
UnitsInStock
Selecting Specific Rows with WHERE
WHERE -
21
SELECT <list of columns>
FROM <table name>
[WHERE <condition list>]
General�Form
Why condition list?
WHERE Examples
22
SELECT ProductName, UnitPrice
FROM Products
WHERE UnitPrice < 15;
- Give the names and unit prices of products that are less than $15.
UnitPrice
UnitsInStock
WHERE Examples
23
SELECT LastName, FirstName, HireDate
FROM Employees
WHERE HireDate >= ‘2014-01-01’;
- Give the names of any employees hired on or after �Jan 1 2014.
Notice the way we format a date literal.
UnitPrice
UnitsInStock
Boolean Expression Operators
24
Operator | Meaning | Example |
= | Equal to | InvoiceId = 2 |
<> | Not equal to | Name <> 'U2' |
< or > | Less/Greater than | UnitPrice < 5 |
<= or >= | Less/Greater than or equal to | UnitPrice >= 0.99 |
LIKE | Matches pattern | PostalCode LIKE 'T2%' |
IN | Within a set | City IN ('Calgary', 'Edmonton') |
IS or IS NOT | Compare to NULL | ReportsTo IS NULL |
BETWEEN | Inclusive range (esp. dates) | UnitPrice BETWEEN 0.99 AND 1.99 |
WHERE Examples
25
SELECT ProductName, UnitPrice
FROM Products
WHERE SupplierID = 7 AND UnitPrice < 15 ;
- Give the names and unit prices of products from supplier with id 7 that are less than $15..
UnitPrice
UnitsInStock
WHERE Examples
26
SELECT OrderID
FROM Orders
WHERE CustomerID = 5 OR CustomerID = 12;
- Give a list of all orders placed by customer with id 5 or customer with id 12. Only return OrderID.
UnitPrice
UnitsInStock
UnitPrice
UnitsInStock
WHERE - IN operator
27
SELECT CompanyName, ContactName
FROM Customers
WHERE Region IN (‘British Isles’, ‘Central America’);
- The boss wants a list of our customers’ company names and contact names for all customers in the British Isles or Central America.
WHERE - LIKE Operator
SELECT CustomerID, CompanyName
FROM Customers
WHERE CompanyName LIKE ‘fo%’;
WHERE - Your Turn
1. Provide a list of products from the supplier with id of 12 that cost more than $25.
29
UnitPrice
UnitsInStock
WHERE - Your Turn
2. Customer relations wants a list of all customer info for any customer in Boston or New York (cities).
30
Adding the ORDER BY Clause
Sorting the Results
Specify the ordering of the rows in the output.
For each attribute in order by clause, ASC (default) or DESC can be specified.
32
SELECT <list of columns>
FROM <table name>
[WHERE <condition list>]
[ORDER BY <column-order list>];
General Form
Sorting the Results
Specify the ordering of the rows in the output.
If <column-order list> contains more than one column, the first column listed is the primary, and the next column is used to break ties when the value in the primary column are equal.
33
SELECT <list of columns>
FROM <table name>
[WHERE <condition list>]
[ORDER BY <column-order list>];
General Form
Output Order Example
34
SELECT ProductName, UnitPrice, UnitsOnOrder
FROM Products
WHERE UnitsOnOrder > 0
ORDER BY ProductName DESC;
- Give the names, unit prices, and number of units in stock for any products we are currently waiting to receive. Sort the list by product name in reverse alphabetical order.
UnitPrice
UnitsInStock
UnitsOnOrder
UnitPrice
UnitsInStock
Output Order Example
35
SELECT CompanyName, City, Country, Region
FROM Customers
ORDER BY Region, CompanyName;
- Provide a list of our customers’ company names with city, country, and region sorted by company name within each region.
Notice…. you aren’t required to have a WHERE clause.
UnitPrice
UnitsInStock
Removing Duplicates
SELECT DISTINCT Country
FROM Customers
ORDER BY Country ASC;
- Provide a list of all Countries where Northwind currently has customers. Sort the result alphabetically.
UnitPrice
UnitsInStock
What do you think?
What do you think the potential difference between the output of these two queries?
37
SELECT DISTINCT ShipCity, ShipCountry
FROM Orders
WHERE shipregion = 'Western Europe'
ORDER BY shipcity, shipcountry;
SELECT ShipCity, ShipCountry
from Orders
where shipregion = 'Western Europe'
order by shipcity, shipcountry;
versus
Aggregate Functions
Aggregate Functions
- Allows us to apply some function to all rows in the result set of a query
- When used alone, resultset will be a single row
- Common aggregate functions:
- MAX
- MIN
- SUM
- AVG
- COUNT
39
SELECT MAX(UnitPrice)
FROM Products;
SELECT COUNT(*)
FROM Products;
Don’t forget… you can alias these to more readable column names for the output.
Aggregate Function Practice
What’s the average price of all products we sell?
What’s the average price of all non-discontinued products we sell?
40
Aggregate Function Practice
What is the date of the first order we ever processed?
How many orders has “Alfreds Futterkiste” placed with us?
41
SET Operations
Union
43
SELECT City
FROM Employees
WHERE Region = 'Western Europe'
UNION ALL
SELECT City
FROM Customers
WHERE Region = 'Western Europe';
Provide a list of all cities in Western Europe where either employees live or customers are based.
Includes duplicates
Use UNION (without ALL) to remove dupes
Intersection
44
SELECT City
FROM Employees
WHERE Country = 'USA'
INTERSECT
SELECT City
FROM Customers
WHERE Country = 'USA';
Provide a list of all cities in the USA where we have BOTH employees and customers.
There’s no ALL version with Intersect
Except
45
SELECT City
FROM Employees
WHERE Country = 'USA'
EXCEPT
SELECT City
FROM Customers
WHERE Country = 'USA';
Provide a list of all cities in the USA where Employees live but where we have no customers.