Small, useful pieces of C# and SQL with an explanation, ready to copy.
Every C# snippet is the exact code that is unit tested for this site. The SQL is tested on SQLite; it is standard window-function SQL but may need small changes for SQL Server or another database. Always try it on a copy of your data first.
Finds rows that share an e-mail address and removes all but the newest one. Run it as a SELECT first to see what would go.
SQLcleanupwindow-functions
DELETE FROM customers
WHERE id IN (
SELECT id FROM (
SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at DESC, id DESC) AS rn
FROM customers
) t
WHERE rn > 1
);
Running total
A cumulative sum in date order without a self-join, using a window function.
SQLreportingwindow-functions
SELECT order_date, amount,
SUM(amount) OVER (ORDER BY order_date, id) AS running_total
FROM orders
ORDER BY order_date, id;
Top 3 per group
The three most expensive products in every category, with a stable tie-break on id.
SQLreportingwindow-functions
SELECT category, name, price
FROM (
SELECT category, name, price,
ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC, id) AS rn
FROM products
) t
WHERE rn <= 3
ORDER BY category, rn;
Find gaps in a sequence
Lists the first missing number of every gap, for example to audit invoice or ticket numbers.
SQLauditjoins
SELECT a.id + 1 AS first_missing
FROM numbers a
LEFT JOIN numbers b ON b.id = a.id + 1
WHERE b.id IS NULL AND a.id < (SELECT MAX(id) FROM numbers)
ORDER BY a.id;