Cheat-Sheets

SQL

Having

Example

orderid custid val
1 101 100
2 101 200
3 102 300
4 103 150
5 103 200
6 104 400
SELECT 
    orderid, custid, SUM(val) as total_sales
FROM Sales
GROUP BY orderid, custid
HAVING SUM(val) > 250
ORDER BY total_sales DESC
orderid custid total_sales
6 104 400
3 102 300

Window functions

Example

Order by val in each partition, then assign a row number to each row by partition.

orderid custid val
1 101 300
2 101 200
3 102 400
4 101 100
5 102 300
SELECT orderid, custid, val,
ROW_NUMBER() OVER(
    PARTITION BY custid
    ORDER BY val) AS rownum
FROM Sales
ORDER BY custid, val; 
orderid custid val rownum
4 101 100 1
2 101 200 2
1 101 300 3
5 102 300 1
3 102 400 2

Predicates

Data types in operations

Case

Examples

SELECT productid, productname, categoryid, 
    CASE categoryid 
        WHEN 1 THEN 'Beverages' 
        WHEN 2 THEN 'Solid food' 
        ELSE 'Unknown Category' 
    END  
AS categoryname 
FROM Products; 
...
    CASE  
        WHEN price < 7 THEN '5%'  
        WHEN price <= 10 THEN '10%'  
        WHEN price > 10 THEN '15%'
... 

Joins

Union

Example

SELECT productid, productname, categoryid FROM products_2023 
UNION {ALL} 
SELECT productid, productname, categoryid FROM products_2024;

Intersect

Example

SELECT productid, productname, categoryid FROM products_2023 
INTERSECT {ALL} 
SELECT productid, productname, categoryid FROM products_2024;

Query evaluation order

The SQL query evaluation order is roughly:

  1. FROM
  2. JOIN (if present)
  3. WHERE
  4. GROUP BY
  5. Aggregations
  6. HAVING
  7. SELECT
  8. ORDER BY

Therefor, if we define an alias in the select clause we cannot reference it in the having clause because it’s evaluated before! However, we can use it in the order by.