Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

SQL Cheat Sheet

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

SQL Cheat Sheet

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

SQL Cheat Sheet productlines

productLine

products

productCode

orderdetails

orderNumber

textDescription
productName
productCode

This cheat sheet provides a quick reference for common SQL htmlDescription
productLine
quantityOrdered

operations and functions, adapted to work with the Classic image productScale
priceEach

Models database structure. 

 productVendor


orderLineNumber

productDescription

The examples use tables such as products, orders, customers, employees

quantityInStock

employees, offices, orderdetails, productlines, and payments employeeNumber

buyPrice
orders

as shown in the database diagram.

lastName

MSRP orderNumber

firstName

orderDate

This structure represents a model car business, so the extension

customers
requiredDate

examples have been tailored to fit this context. email

customerNumber
shippedDate

officeCode

customerName
status

reportsTo

contactLastName
comments

jobTitle
contactFirstName
customerNumber

phone

offices
addressLine1

officeCode
addressLine2

payments

city
city

customerNumber

phone
state

checkNumber

addressLine1
postalCode

paymentDate

addressLine2
country

amount
state
salesRepEmployeeNumber

country
creditLimit
postalCode

territory

SQL Cheat Sheet Find more free resources at dataquest.io/guide/sql


Table of Contents
Selection Queries Aggregate Functions String Functions
Select, Order By, Distinct Sum, Avg, ROUND, Min, Max, Upper, Lower, Length, SUBSTR,
Group By, HAVING, COUNT Concatenation

Conditional Queries Combine Data Window Functions


Case, COALESCE, Cast Union, Union All, Except, Partition BY, Order By,
Intersect PARTITION BY AND ORDER BY

Ranking Functions Joins Subqueries


DENSE_RANK, RANK, Row Number, Inner Join, Left Join, Right Join, SELECT, FROM, WHERE, IN, EXISTS,
NTile Cross Join, JOIN MULTIPLE, JOIN SELF Correlated Subquery, =, CTE

SQLite and PostgreSQL


SQLite-specific commands, 

PostgreSQL-specific commands

SQL Cheat Sheet Find more free resources at dataquest.io/guide/sql


Selection Queries Aggregate Functions

Clause How to use Explained Clause How to use Explained

Select SELECT * 
Display all columns from SUM SELECT SUM(quantityOrdered * priceEach) 
 Calculates the total sales
FROM products; products table. AS total_sales
from the orderdetails
FROM orderdetails; table.
SELECT productName, buyPrice
Display only productName
FROM products; and buyPrice columns from
products table.
AVG SELECT AVG(buyPrice) AS average_price
Averages the buyPrice
FROM products; values in products.
Order By SELECT productName, buyPrice
Sort the selected columns by
FROM products
buyPrice in descending
ORDER BY buyPrice DESC; order.
ROUND SELECT ROUND(AVG(buyPrice), 2)
Rounds the average of
AS average_price
buyPrice to two decimal
SELECT productName, buyPrice
 Sort the selected columns by
productName in ascending
FROM products; places.
FROM products

ORDER BY productName ASC;
order.
MIN SELECT MIN(buyPrice) AS lowest_price
 Finds the minimum value in
FROM products; the buyPrice column of
SELECT orderNumber, customerNumber,
Sorts the data by
customerNumber and then products.
orderDate, status

FROM orders

by orderDate within each
ORDER BY customerNumber ASC, orderDate DESC;
customerNumber. MAX SELECT MAX(buyPrice) AS highest_price
Finds the maximum value in
FROM products; the buyPrice column of
products.
Distinct SELECT DISTINCT productLine
Retrieve unique values from
FROM products; productLine in products
table. COUNT SELECT COUNT(*) AS total_orders
Counts the total number of
FROM orders; rows in orders.

SELECT DISTINCT city, country
Retrieve unique
FROM customers
combinations of city and
ORDER BY country, city; country where customers Note COUNT(*) includes all rows, while COUNT(column_name) excludes NULL values in the specified column.
are located, sorted by
country and then city.

SQL Cheat Sheet Find more free resources at dataquest.io/guide/sql


Aggregate Functions

Clause How to use Explained Clause How to use Explained

GROUP BY SELECT productLine, AVG(buyPrice) 
 Groups rows by HAVING SELECT productLine, AVG(buyPrice)
Filters product lines to only
AS avg_price
productLine and AS avg_price
include those with average
FROM products
calculates the average FROM products
price greater than 50.
GROUP BY productLine; price for each product line. GROUP BY productLine

HAVING AVG(buyPrice) > 50;

SELECT productLine, AVG(buyPrice)


Groups rows by
productLine for products COUNT Counts the total number of
AS avg_price
SELECT COUNT(*) AS total_products

FROM products
FROM products; rows in the products table,
with price over 100 and
WHERE buyPrice > 100
returning the total number of
calculates the average price
GROUP BY productLine; products. This includes all
for each product line.
rows, regardless of NULL
values in any columns.
SELECT customerNumber, COUNT(orderNumber)
Groups orders by
AS order_count
customerNumber, counts the
FROM orders
number of orders for each
SELECT COUNT(reportsTo)
Counts the number of non-
WHERE orderDate >= '2023-01-01'
customer in 2023 and AS employees_with_manager
 null values in the reportsTo
GROUP BY customerNumber

beyond, and sorts the results FROM employees; column of the employees
ORDER BY order_count DESC;
by the order count in table, showing how many
descending order.

employees have a manager


assigned.

This shows which customers


placed the most orders in COUNT ignores NULL values,
2023. so employees without a
manager (e.g., the president)
are not included in this
count.

SQL Cheat Sheet Find more free resources at dataquest.io/guide/sql


String Functions

Clause How to use Explained Clause How to use Explained

upper SELECT UPPER(productName)


Converts the productName SELECT SUBSTR(productCode, -4)
Extracts the last four
AS uppercase_name
column values to uppercase. AS product_id, productCode
characters from the
FROM products; FROM products; productCode column.

lower SELECT LOWER(productName)


Converts the productName
Concat
SELECT firstName || ' ' || lastName
Concatenates firstName
AS lowercase_name
column values to lowercase. using || AS full_name
and lastName with a space
FROM products;
FROM employees; in between.

length SELECT productName, LENGTH(productName)


Calculates the length of each
AS name_length
value in the productName SELECT firstName || '.' || lastName ||
Creates an email address by
FROM products; column. '@classicmodelcars.com'
concatenating firstName,
AS email_address
 lastName, and domain.
FROM employees;

SUBSTR SELECT SUBSTR(productLine, 1, 3)


Extracts the first three
AS product_category, productLine
characters from the
FROM products; productLine column.
SUBSTR extracts a substring
from a given string.

It can be used to extract


characters from the
beginning, end, or any
position within the string.

SQL Cheat Sheet Find more free resources at dataquest.io/guide/sql


Conditional Queries

Clause How to use Explained Clause How to use Explained

Case SELECT productName,


Categorizes the buyPrice Coalesce SELECT productName,
Returns 'No description
buyPrice,
values into Budget, Mid- COALESCE(productDescription,
available' if
CASE
range, and Premium 'No description available')
productDescription is
WHEN buyPrice < 50 THEN
categories. AS product_description
null.
'Budget'
FROM products;
WHEN buyPrice BETWEEN 50

AND 100 THEN 'Mid-range'


Returns the first non-null
SELECT employeeNumber,

ELSE 'Premium'

firstName,
value among extension,
END AS price_category

lastName,
email, or 'No contact
FROM products;
COALESCE(extension, email, 'No
information'.
contact information') AS contact_info

SELECT orderNumber,
Categorizes orders into FROM employees;
orderDate,
different sale seasons based
CASE
on the order date.
WHEN CAST(strftime('%m',
Converts the orderDate to
Cast SELECT orderNumber, CAST(orderDate AS DATE)

orderDate) AS INTEGER)

AS order_day
DATE type.
BETWEEN 3 AND 5 THEN

FROM orders;
'Spring Sale'


WHEN CAST(strftime('%m',

orderDate) AS INTEGER)

BETWEEN 6 AND 8 THEN

'Summer Sale'

WHEN CAST(strftime('%m',

orderDate) AS INTEGER)

BETWEEN 9 AND 11 THEN

'Fall Sale'

ELSE 'Winter Sale'

END AS sale_season

FROM orders;

SQL Cheat Sheet Find more free resources at dataquest.io/guide/sql


Combine Data

Clause How to use Explained Clause How to use Explained

union SELECT productName


Combines the product names intersect SELECT customerNumber, customerName
Returns customers who are
FROM products
from ‘Classic Cars’ and FROM customers
both located in the USA and
WHERE productLine = 'Classic Cars'
‘Vintage Cars’ product lines, WHERE country = 'USA'
have a credit limit over
UNION
removing duplicates. INTERSECT
100,000.

SELECT productName
SELECT customerNumber, customerName

FROM products
FROM customers

WHERE productLine = 'Vintage Cars'; WHERE creditLimit > 100000;


This query demonstrates how
INTERSECT finds common
rows between two result sets.

union all SELECT productName


Combines the product names
FROM products
from ‘Classic Cars’ and Note EXCEPT and INTERSECT are not supported in all SQL databases. These examples use
WHERE productLine = 'Classic Cars'
‘Vintage Cars’ product lines PostgreSQL syntax.
UNION ALL
without removing duplicates.
SELECT productName

FROM products

WHERE productLine = 'Vintage Cars';

except SELECT productCode, productName


Returns products EXCEPT the
FROM products
‘Classic Cars’ product line,
EXCEPT
demonstrating how EXCEPT
SELECT productCode, productName
removes rows from the first
FROM products

result that appear in the


WHERE productLine = 'Classic Cars';
second result.

SQL Cheat Sheet Find more free resources at dataquest.io/guide/sql


Window Functions Ranking Functions
Note SQLite does not support window functions natively. The following examples use PostgreSQL syntax and require Note SQLite does not support ranking functions natively. The following examples use PostgreSQL syntax and require
PostgreSQL or a SQLite extension. PostgreSQL or a SQLite extension.

Clause How to use Explained Clause How to use Explained

PARTITION
SELECT employeeNumber,
Calculates the average Dense
SELECT productCode,
select emp_id, sal_amount,

sal_date,
 Ranks products based on
BY officeCode,
extension length within each Rank dense_ran k() over (


productName, buyPrice in descending


extension,
office. The PARTITION BY byPmonth_salar
orderbuy rice,
y
 order. Differs from RANK by
AVG(LENGTH(extension)) OVER (
clause divides the data into Dk
ENSE_RANK() OVER (

) as ran handling ties differently (no


PARTITION BY officeCode
from salaryORDER BY buyPrice DESC

partitions based on the gaps in ranking).


) AS avg_extension_length
) AS price_rank

officeCode column.
FROM employees; FROM products;

ORDER BY SELECT employeeNumber, 
 Calculates a running total of RANK SELECT employeeNumber,


select emp_id, sal_amount,

sal_date,
 Ranks employees within
officeCode,
 extension lengths ordered by dense_ran k() over (


officeCode, each office based on their


extension,
 by month_salary

orderextension,
extension length. Differs
length in descending order.
SUM(LENGTH(extension)) OVER (
 ) as rank
 K() OVER (

RAN from DENSE_RANK by leaving


from salaryPARTITION BY officeCode

ORDER BY LENGTH(extension) DESC
 gaps in ranking when there


) AS running_total_length
 ORDER BY LENGTH(extension) DESC

are ties.
FROM employees; ) AS extension_rank_in_office

FROM employees;

PARTITION
SELECT employeeNumber, 
 Calculates a running total of
BY

ROW
SELECT
select orderNumber,
emp_id, sal_amount,

sal_date,
 Assigns a unique row
officeCode,
 extension lengths within
NUMBER dense_ran k()Date,

order over (
 number to each order based


extension,
 each office, ordered by
ORDER BY by month_salary

ordercustomerNumber,
on orderDate and
SUM(LENGTH(extension)) OVER (
 length.
PARTITION BY officeCode
 ROW_NUMBER
) as rank
 () OVER (
customerNumber.
ORDER BY LENGTH(extension) DESC
 from salaryORDER BY orderDate,

) AS running_total_length
 customerNumber

FROM employees; ) AS order_number

FROM orders;

SQL Cheat Sheet Find more free resources at dataquest.io/guide/sql


Joins
Clause How to use Explained Clause How to use Explained

INNER
SELECT o.orderNumber,
 Joins orders and CROSS
SELECT p.productName,
 Returns all possible
JOIN o.orderDate,
 customers tables, returning JOIN pl.textDescription
 combinations of products
c.customerName
 only matching rows. This is FROM products AS p
 and product line
FROM orders AS o
 the default join type when CROSS JOIN productlines AS pl; descriptions.
INNER JOIN customers AS c

JOIN is used without
ON o.customerNumber = c.customerNumber;
specifying LEFT, RIGHT, or
FULL.
join
SELECT o.orderNumber,
Joins four tables: orders,
LEFT
Joins products and 
multiple c.customerName,
customers, orderdetails,
SELECT p.productCode,

JOIN p.productName,
 orderdetails tables, p.productName
and products.
od.orderNumber
 returning all products and FROM orders AS o

FROM products AS p
 JOIN customers AS c

their orders (if any).


LEFT JOIN orderdetails AS od
 ON o.customerNumber = c.customerNumber

ON p.productCode = od.productCode; JOIN orderdetails AS od

ON o.orderNumber = od.orderNumber

JOIN products p

ON od.productCode = p.productCode;
RIGHT
SELECT e.employeeNumber,
 Joins offices and

JOIN e.lastName,
 employees tables, returning


o.officeCode
 all employees and their
FROM offices AS o
 JOIN SELF SELECT e1.firstName || ' ' || e1.lastName Self-join example listing
offices (if any).
RIGHT JOIN employees AS e
 AS employee,
 employees and their
ON o.officeCode = e.officeCode; e2.firstName || ' ' || e2.lastName respective managers.
AS manager

FROM employees AS e1

LEFT JOIN employees AS e2

ON e1.reportsTo = e2.employeeNumber;

SQL Cheat Sheet Find more free resources at dataquest.io/guide/sql


Subqueries
Clause How to use Explained Clause How to use Explained

Subquery
SELECT productName,
Includes a subquery that Subquery
SELECT productName,
Finds products that were
in SELECT buyPrice,
calculates the average price with IN
buyPrice
ordered in order 10100.
(SELECT AVG(buyPrice) FROM
for all products. FROM products

products) AS avg_price
WHERE productCode IN (

FROM products; SELECT productCode

FROM orderdetails

WHERE orderNumber = 10100

Subquery
SELECT productLine,
Finds product lines with an );
in FROM avg_price
average price greater than
FROM (SELECT productLine,
100 using a subquery.
AVG(buyPrice) AS avg_price
Subquery
his query retrieves the
SELECT customerName
 T

FROM products
with

FROM customers c
 names of customers who


GROUP BY productLine)
EXISTS
WHERE EXISTS (
 have placed at least one
AS line_averages

WHERE avg_price > 100;


SELECT 1

order on or after January 1,
FROM orders o

2023.
WHERE o.customerNumber

= c.customerNumber


Subquery
SELECT productName,
This query selects products AND o.orderDate >= '2023-01-01'

in WHERE buyPrice
that are more expensive than );
FROM products p1
the average price in their
WHERE p1.buyPrice > (
respective product line,
SELECT AVG(p2.buyPrice)

ordered by product line and


FROM products p2

price in descending order.


WHERE p1.productLine =

p2.productLine)

ORDER BY productLine,

buyPrice DESC;

SQL Cheat Sheet Find more free resources at dataquest.io/guide/sql


Subqueries SQLite and PostgreSQL
Clause How to use Explained SQLite Commands

= SELECT orderNumber, 
 This query selects all orders .tables Lists all tables in the current database.
orderDate, 
 for a specific customer
totalAmount
 named ‘Mini Gifts .schema table_name Shows the schema for the specified table.
FROM orders
 Distributors Ltd.’, ordered by
WHERE customerNumber = (

date from most recent to .mode column
Sets output to column mode with headers
SELECT customerNumber

oldest. .headers on for better readability.
FROM customers

WHERE customerName = 'Mini Gifts

Distributors Ltd.'
 .open filename Opens a new or existing database file.


)

ORDER BY orderDate DESC;
.save filename Saves the current database to a file.

.quit Exits the SQLite prompt.


CTE WITH order_totals AS (
This query calculates the
SELECT orderNumber,
total amount for each order
SUM(quantityOrdered * priceEach)
using a CTE and then joins
AS total_amount
the orders table with the
FROM orderdetails

CTE to display order details


GROUP BY orderNumber

with total amounts, ordered


)

SELECT o.orderNumber,
by total amount in
o.orderDate,
descending order.
ot.total_amount

FROM orders o

JOIN order_totals ot

ON o.orderNumber = ot.orderNumber

ORDER BY ot.total_amount DESC;

SQL Cheat Sheet Find more free resources at dataquest.io/guide/sql


SQLite and PostgreSQL
PostgreSQL Commands

\l Lists all databases.

\c database_name Connects to a specific database.

\dt Lists all tables in the current database.

\d table_name Describes the specified table.

\du Lists all roles/users.

\timing Toggles display of query execution time.

\e Opens the last command in an editor.

\i filename Executes commands from a file.

\q Exits the PostgreSQL interactive terminal.

Note SQLite doesn’t have a built-in user management system like PostgreSQL, so commands related to user
management are not applicable.

SQL Cheat Sheet Find more free resources at dataquest.io/guide/sql

You might also like