Snippets·Grátis
Snippets de SQL
20 snippets de SQL: CTEs, upserts, funções de janela, linhas sem correspondência, paginação por chave, índices e transações. Testamos cada um no SQLite.
Instalação grátis.
Se o PocketCode estiver instalado no seu Android, isto abre a página no app.
Prévia
5 de 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;Mudanças na 1.0.0
Primeira versão.