🫐SQL Cheatsheet
Last updated
Last updated
Constraint | Explanation | Rules | SQL Example |
---|---|---|---|
Primary Key | Uniquely identifies each record in a table. Only one primary key allowed. | - Column(s) must be unique - Cannot contain null values - Limited to one per table |
|
Foreign Key | Links to primary key in another table. Enforces referential integrity. | - Column(s) must match type of referenced column(s) - Values must exist in referenced table |
|
Unique | Ensures values in column are unique. Only distinct values allowed. | - Column(s) cannot contain duplicate values |
|
Not Null | Mandates column cannot contain NULL values. | - Column cannot contain null values |
|
Check | Validates values against logical expression. | - Inserted/updated values must evaluate to true |
|
Default | Sets default value if none provided. | - Default value is inserted if no other value specified |
|
Index | Improves lookup performance on columns. | - Can be unique or non-unique - Single column or multiple columns |
|
Join Type | Explanation | Rules | Example |
---|---|---|---|
INNER JOIN | Returns records that have matching values in both tables | Matches rows from the first table with rows from the second table where the join condition is met |
|
LEFT JOIN | Returns all records from the left table, and the matched records from the right table | Returns all rows from the left table, along with any matching rows from the right table |
|
RIGHT JOIN | Returns all records from the right table, and the matched records from the left table | Returns all rows from the right table, along with any matching rows from the left table |
|
FULL OUTER JOIN | Returns all records when there is a match in either left or right table | Returns rows when there is a match in one of the tables |
|
CROSS JOIN | Returns rows combined by cartesian product between two tables | No join condition needed, combines every row from the first table with every row from the second table |
|
Term | Explanation | Rules | Example |
---|---|---|---|
GROUP BY | Used to group rows that have the same values into summary rows | Used after the FROM and WHERE clauses. Must be used with aggregate functions like COUNT, MAX etc |
|
GROUP BY Column | Groups rows based on values in the specified column | Column used in GROUP BY must be present in the SELECT statement |
|
GROUP BY Multiple Columns | Groups rows based on multiple column values | List multiple columns in GROUP BY to group on combinations of values |
|
HAVING | Filters grouped rows that meet a specified condition | Goes after GROUP BY. Can reference aggregated columns |
|
ROLLUP | Provides subtotals at different grouping levels | Used after GROUP BY, provides extra super-aggregate rows |
|