SQL Cheat Sheet
Last updated on 2023-10-19 | Edit this page
Basic Queries
Select one or more columns of data from a table:
Select all of the columns in a table:
Get only unique lines in a query:
Perform calculations in a query:
Filtering
Select only the data meeting certain criteria:
Combine conditions:
Sorting
Sort results using ASC for ascending order or
DESC for descending order:
Missing Data
Use NULL to represent missing data.
NULL is neither true nor false. Operations involving
NULL produce NULL, e.g., 1+NULL,
2>NULL, and 3=NULL are all
NULL.
Test whether a value is null:
Test whether a value is not null:
Grouping and Aggregation
Combine data into groups and calculate combined values in groups:
Joins
Join data from two tables:
Combining Commands
SQL commands must be combined in the following order:
SELECT, FROM, JOIN,
ON, WHERE, GROUP BY,
ORDER BY.
Creating Tables
Create tables by specifying column names and types. Include primary and foreign key relationships and other constraints.
Transactions
Put multiple queries in a transaction to ensure they are ACID (atomic, consistent, isolated, and durable):
Programming
Execute queries in a general-purpose programming language by:
- loading the appropriate library
- creating a connection
- creating a cursor
- repeatedly:
- execute a query
- fetch some or all results
- disposing of the cursor
- closing the connection
Python example: