SQL Notes
TL;DR
Notes on SQL. This is at an introductory level.
Basic Syntax
SELECT
You can specify the column names you want to see. This is the foundation of everything.
DISTINCT
Adding DISTINCT eliminates duplicates. It can be used in contexts other than SELECT as well.
WHERE
You can specify conditions.
ORDER BY
Sort by a condition. DESC is required for descending order.
JOIN
There are inner joins (INNER JOIN) and outer joins (LEFT OUTER JOIN). It works the same way as in pandas.
IFNULL, COALESCE
IFNULL: Specify a default value when a value is NULL.COALESCE: Examines multiple columns and returns a default value if NULL.
LIMIT
Limits the number of records retrieved.
OFFSET
Specifies which record number to start retrieving from. Often used in combination with sorting.
Variable Definition
DECLARE may be required.
Comparison
Checking if NULL:
Standard comparison operators work for greater/less than comparisons. For equality, use = instead of ==.
Window Functions
Unlike GROUP BY which aggregates rows, window functions create a new column without aggregating. Use PARTITION BY to specify which column to target. Both regular aggregate functions and window function-specific functions can be used.
Basics
ORDER BY
ORDER BY within a window function specifies the order in which the window function processes rows. When using SUM, it gives the cumulative sum up to the current row.
ROW
You can specify from where to where processing should occur.
The following variables can be used for start and end positions:
| name | description |
|---|---|
| CURRENT ROW | Current row |
| UNBOUNDED PRECEDING | Start of the PARTITION |
| UNBOUNDED FOLLOWING | End of the PARTITION |
| N(INT) PRECEDING | N rows before the current row |
| N(INT) FOLLOWING | N rows after the current row |