Skip to content
Snippets·Free

SQL snippets

20 SQL snippets: CTEs, upserts, window functions, rows without a match, keyset pagination, indexes and transactions. We ran every one against SQLite.

Free to install.

If PocketCode is installed on your Android device, this opens the page in the app.

Preview

5 of 20

Common table expressioncte

Name a subquery with WITH and select from it

WITH ${1:recent} AS (
  SELECT ${2:*}
  FROM ${3:orders}
  WHERE ${4:created_at >= '2024-01-01'}
)
SELECT ${5:*}
FROM ${1:recent};

Upsertupsert

Insert a row or update it when the key already exists

INSERT INTO ${1:settings} (${2:key}, ${3:value})
VALUES (${4:'theme'}, ${5:'dark'})
ON CONFLICT (${2:key}) DO UPDATE SET ${3:value} = excluded.${3:value};

Rows without a matchleftnull

LEFT JOIN that keeps only the rows missing on the other side

SELECT ${1:u}.*
FROM ${2:users} ${1:u}
LEFT JOIN ${3:orders} ${4:o} ON ${4:o}.${5:user_id} = ${1:u}.id
WHERE ${4:o}.${5:user_id} IS NULL;

Group with HAVINGgrouphaving

Count per group and keep the groups above a threshold

SELECT ${1:customer_id}, COUNT(*) AS ${2:total}
FROM ${3:orders}
GROUP BY ${1:customer_id}
HAVING COUNT(*) > ${4:5}
ORDER BY ${2:total} DESC;

Latest row per grouprownum

ROW_NUMBER over a partition to pick the newest row of each group

SELECT *
FROM (
  SELECT ${1:*},
         ROW_NUMBER() OVER (PARTITION BY ${2:user_id} ORDER BY ${3:created_at} DESC) AS rn
  FROM ${4:orders}
) ranked
WHERE rn = 1;

Changes in 1.0.0

First version.

Related