ToolHop.

ADVERT

๐Ÿ—„๏ธ SQL Cheatsheet

SQL command reference for SELECT queries, filtering, joins, aggregation, schema changes, and performance tips.

SQL query patterns that power dashboards, reporting, and migrations. Copy the essentials for filtering, joining, aggregating, and managing schema.

SELECT Essentials

Build reliable projections and calculations.

QueryPurposeNotes
SELECT * FROM customers LIMIT 50;Sample dataUse LIMIT for fast previews; replace * with named columns in production.
SELECT name, email FROM users ORDER BY created_at DESC;Sorted projectionORDER BY supports ASC/DESC and multi-column priority.
SELECT DISTINCT country FROM orders;Unique valuesDISTINCT applies to the full set of selected columns.
SELECT NOW() AS server_time;Built-in functionsPopular helpers: NOW(), CURRENT_DATE, LOWER(), UPPER(), LENGTH().

Filtering & Time

Target precise records with WHERE clauses.

QueryPurposeNotes
SELECT * FROM orders WHERE status = 'paid';Equality filterUse parameterized queries to avoid SQL injection.
SELECT * FROM orders WHERE total BETWEEN 50 AND 200;Range filterBETWEEN is inclusive; combine with decimals for price bands.
SELECT * FROM users WHERE email LIKE '%@toolhop.app';Pattern searchEscape % or _ when matching literal characters.
SELECT * FROM events WHERE occurred_at >= NOW() - INTERVAL '7 days';Relative timeIntervals vary by database (INTERVAL, DATEADD, DATE_SUB).

Joins & Aggregations

Combine tables and summarize metrics.

QueryPurposeNotes
SELECT * FROM orders o JOIN customers c ON c.id = o.customer_id;Inner joinReturn rows where both tables match.
SELECT * FROM posts p LEFT JOIN comments c ON c.post_id = p.id;Left joinReturn all posts even when comments are missing.
SELECT city, COUNT(*) FROM users GROUP BY city;AggregationColumns in SELECT must be aggregated or appear in GROUP BY.
SELECT city, COUNT(*) FROM users GROUP BY city HAVING COUNT(*) > 100;Aggregation filterHAVING filters aggregated results after GROUP BY.

Schema & Indexing

DDL commands you reach for during migrations.

Create table

Define columns, constraints, and default values.

CREATE TABLE accounts (
  id SERIAL PRIMARY KEY,
  email TEXT UNIQUE NOT NULL,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

Alter table

Add/remove columns or constraints with ALTER.

ALTER TABLE accounts ADD COLUMN last_login TIMESTAMPTZ;

Indexes

Add indexes to columns used in joins or WHERE filters.

CREATE INDEX idx_orders_customer_id ON orders (customer_id);

Upserts

UPSERT prevents duplicate keys and keeps counts fresh.

INSERT INTO inventory (sku, qty) VALUES ($1, $2)
ON CONFLICT (sku) DO UPDATE SET qty = excluded.qty;

Optimization Tips

Keep queries fast and resource-friendly.

  • Explain plans

    Use EXPLAIN (ANALYZE, BUFFERS) SELECT ... to inspect query cost.

  • Limit result size

    Paginate with LIMIT/OFFSET or keyset pagination for deep scrolls.

  • Avoid SELECT *

    Select only necessary columns to reduce network and cache pressure.

  • Batch writes

    INSERT ... VALUES (),(),() avoids chattiness.

  • Use transactions

    BEGIN; ... COMMIT; ensures integrity across multiple statements.

ADVERT

ADVERT

SQL Cheatsheet - SELECT, Joins, Aggregates & Schema