SQL code examples
12 short, tested snippets. Pick one to see the code with notes, or search Zest for something specific, such as “sql select with where and order by”.
- SELECT with WHERE and ORDER BYSELECT id, name, created_at
- JOIN types-- only rows that match in both tables
- GROUP BY and HAVINGSELECT customer_id, COUNT(*) AS orders, SUM(total) AS spent
- INSERT, UPDATE and DELETEINSERT INTO users (name, email) VALUES ('Ann', 'ann@example.com');
- CREATE TABLECREATE TABLE orders (
- Create an indexCREATE INDEX idx_orders_customer ON orders (customer_id);
- Common table expression (WITH)WITH recent AS (
- Window function: ROW_NUMBERSELECT *
- Upsert (insert or update)-- PostgreSQL / SQLite
- PaginationSELECT * FROM posts ORDER BY id LIMIT 20 OFFSET 40; -- page 3
- CASE expressionSELECT name,
- Find duplicatesSELECT email, COUNT(*) AS n