SQL Snippets
SQL snippets for finding duplicates, window functions and everyday queries. Tested on SQLite and DuckDB; standard syntax that also runs on PostgreSQL.
duplicates
Find and delete duplicate rows
Count duplicated values, list the extra rows with ROW_NUMBER(), and delete them while keeping the first row per group.
-- 1. Which values appear more than once?
SELECT email, COUNT(*) AS occurrences
FROM users
GROUP BY email
HAVING COUNT(*) > 1
ORDER BY occurrences DESC;
-- 2. Show the duplicate rows themselves (the first row per email is kept, the rest listed)
SELECT *
FROM (
SELECT u.*,
ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn
FROM users u
) t
WHERE rn > 1;
-- 3. Delete the duplicates, keeping the lowest id per email
DELETE FROM users
WHERE id IN (
SELECT id FROM (
SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn
FROM users
) t
WHERE rn > 1
);Find duplicates that differ only by case or spaces
Group on LOWER(TRIM(column)) to catch near-duplicate emails or usernames, and show which row would be kept.
-- Rows whose email differs only by case or surrounding spaces
SELECT LOWER(TRIM(email)) AS normalized_email,
COUNT(*) AS occurrences,
MIN(id) AS keep_id
FROM users
GROUP BY LOWER(TRIM(email))
HAVING COUNT(*) > 1
ORDER BY occurrences DESC, normalized_email;
-- List every row in those groups next to the row that would be kept
SELECT id,
email,
FIRST_VALUE(id) OVER (PARTITION BY LOWER(TRIM(email)) ORDER BY id) AS keep_id
FROM users
WHERE LOWER(TRIM(email)) IN (
SELECT LOWER(TRIM(email)) FROM users
GROUP BY LOWER(TRIM(email)) HAVING COUNT(*) > 1
)
ORDER BY keep_id, id;window-functions
Running total and moving average
Cumulative sums and rolling averages with SUM() and AVG() window functions, overall and per group.
-- Daily revenue with a running total and a 7-row moving average
SELECT
order_date,
daily_revenue,
SUM(daily_revenue) OVER (ORDER BY order_date) AS running_total,
AVG(daily_revenue) OVER (
ORDER BY order_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS moving_avg_7d
FROM (
SELECT order_date, SUM(amount) AS daily_revenue
FROM orders
GROUP BY order_date
) d
ORDER BY order_date;
-- Running total that restarts for each customer
SELECT
customer_id,
order_date,
amount,
SUM(amount) OVER (
PARTITION BY customer_id
ORDER BY order_date, id
) AS customer_running_total
FROM orders
ORDER BY customer_id, order_date, id;Top N rows per group
Get the top N rows in each group with ROW_NUMBER(), or keep ties with DENSE_RANK().
-- Top 2 most expensive products per category (ties broken by id)
SELECT category, name, price
FROM (
SELECT p.*,
ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC, id) AS rn
FROM products p
) ranked
WHERE rn <= 2
ORDER BY category, rn;
-- Keep ties: every product whose price is in the top 2 distinct prices
SELECT category, name, price
FROM (
SELECT p.*,
DENSE_RANK() OVER (PARTITION BY category ORDER BY price DESC) AS price_rank
FROM products p
) ranked
WHERE price_rank <= 2
ORDER BY category, price DESC, id;Compare with the previous row (LAG / LEAD)
Day-over-day change and percentage change with LAG(), and look-ahead with LEAD(), without a self-join.
-- Day-over-day change using the previous row's value
SELECT
day,
signups,
LAG(signups) OVER (ORDER BY day) AS prev_signups,
signups - LAG(signups) OVER (ORDER BY day) AS change,
ROUND(100.0 * (signups - LAG(signups) OVER (ORDER BY day))
/ NULLIF(LAG(signups) OVER (ORDER BY day), 0), 1) AS pct_change,
LEAD(signups) OVER (ORDER BY day) AS next_signups
FROM daily_signups
ORDER BY day;Find consecutive streaks (gaps and islands)
Group consecutive dates into streaks per user by subtracting ROW_NUMBER() from the date.
-- Streaks of consecutive days per user (gaps and islands)
WITH days AS (
SELECT DISTINCT user_id, login_date
FROM logins
),
grouped AS (
SELECT user_id,
login_date,
-- consecutive dates minus their row number give the same value
login_date - CAST(ROW_NUMBER() OVER (
PARTITION BY user_id ORDER BY login_date) AS INTEGER) AS grp
-- SQLite: julianday(login_date) - ROW_NUMBER() OVER (...) AS grp
FROM days
)
SELECT user_id,
MIN(login_date) AS streak_start,
MAX(login_date) AS streak_end,
COUNT(*) AS days_in_streak
FROM grouped
GROUP BY user_id, grp
ORDER BY user_id, streak_start;Percent of total and percent of group
Compute each row's share of its group and of the grand total with SUM() OVER (), no self-join needed.
-- Each row's share of its group total and of the grand total
SELECT region,
id,
amount,
ROUND(100.0 * amount / SUM(amount) OVER (PARTITION BY region), 1) AS pct_of_region,
ROUND(100.0 * amount / SUM(amount) OVER (), 1) AS pct_of_total
FROM orders
ORDER BY region, amount DESC;
-- One row per group: group total and its share of the grand total
SELECT region,
SUM(amount) AS region_total,
ROUND(100.0 * SUM(amount) / SUM(SUM(amount)) OVER (), 1) AS pct_of_total
FROM orders
GROUP BY region
ORDER BY region_total DESC, region;Counter increase with resets (Prometheus-style)
Turn a cumulative counter into per-sample increases with LAG(), treating any drop in value as a counter reset.
-- Per-sample increase of a cumulative counter, treating a drop as a reset
WITH ordered AS (
SELECT series,
ts,
value,
LAG(value) OVER (PARTITION BY series ORDER BY ts) AS prev_value
FROM counter_samples
)
SELECT series,
ts,
value,
CASE
WHEN prev_value IS NULL THEN NULL -- first sample: no previous value
WHEN value < prev_value THEN value -- counter reset (restart): count from 0
ELSE value - prev_value
END AS increase
FROM ordered
ORDER BY series, ts;
-- Total increase per series over the whole range, resets included
WITH ordered AS (
SELECT series, ts, value,
LAG(value) OVER (PARTITION BY series ORDER BY ts) AS prev_value
FROM counter_samples
)
SELECT series,
SUM(CASE WHEN value < prev_value THEN value ELSE value - prev_value END) AS total_increase
FROM ordered
WHERE prev_value IS NOT NULL
GROUP BY series
ORDER BY series;

