Saltar al contenido
Snippets·Gratis

Snippets de SQL

20 snippets de SQL: CTE, upserts, funciones de ventana, filas sin coincidencia, paginación por clave, índices y transacciones. Probamos cada uno en SQLite.

Se instala gratis.

Si tienes PocketCode instalado en tu Android, esto abre la página en la app.

Vista previa

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;

Cambios en la 1.0.0

Primera versión.

Relacionados