SQLite cheat sheet
Everyday SQLite: one file, one dialect and a few rules of its own, mainly type affinity, dates stored as text and upserts that look a lot like Postgres.
sqlly.app/sql-cheat-sheets/sqlite
SELECT basics
- Everything from a table
SELECT * FROM customers;- First 10 rows, ordered
SELECT * FROM customers ORDER BY last_name LIMIT 10;- Expression with an alias
SELECT first_name || ' ' || last_name AS full_name FROM customers;- Unique values
SELECT DISTINCT country FROM customers;- Conditional value
SELECT name, CASE WHEN points >= 100 THEN 'gold' ELSE 'standard' END AS tier FROM members;
Joins
- Inner join
SELECT o.id, c.name FROM orders o JOIN customers c ON o.customer_id = c.id;- Left join keeps unmatched rows
SELECT c.name, o.id FROM customers c LEFT JOIN orders o ON o.customer_id = c.id;- Both sides, matched or not (3.39+)
SELECT e.name, m.name FROM employees e FULL OUTER JOIN managers m ON m.employee_id = e.id;- Cross join builds combinations
SELECT s.name, m.name FROM sizes s CROSS JOIN materials m;
Filtragem
- Combined conditions
SELECT * FROM orders WHERE country = 'DE' AND placed_at >= '2026-01-01';- Range and lists
SELECT * FROM orders WHERE total BETWEEN 100 AND 500 AND status IN ('new', 'paid');- Case-sensitive pattern with GLOB
SELECT * FROM files WHERE name GLOB '*.log';- Exists elsewhere
SELECT * FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
Aggregation
- Count per group
SELECT country, COUNT(*) AS customers FROM customers GROUP BY country;- Groups after filtering with HAVING
SELECT customer_id, SUM(total) AS spent FROM orders GROUP BY customer_id HAVING SUM(total) > 1000;- Aggregate text with group_concat (ORDER BY: 3.44+)
SELECT country, group_concat(name, ', ' ORDER BY name) FROM customers GROUP BY country;- Rank within a partition
SELECT name, department, RANK() OVER (PARTITION BY department ORDER BY salary DESC) FROM employees;
Insert, update, delete
- Single and multi-row insert
INSERT INTO customers (first_name, last_name) VALUES ('Ada', 'Lovelace'), ('Grace', 'Hopper');- Insert and read back the key (3.35+)
INSERT INTO customers (first_name) VALUES ('Ada') RETURNING id;- Upsert with ON CONFLICT
INSERT INTO stock (sku, count) VALUES ('A1', 5) ON CONFLICT (sku) DO UPDATE SET count = count + excluded.count;- Insert or replace wholesale
INSERT OR REPLACE INTO settings (key, value) VALUES ('theme', 'dark');- Update from another table (3.33+)
UPDATE products SET price = p.price FROM prices p WHERE p.sku = products.sku;
Create, alter, drop
- Create a table
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL REFERENCES customers (id), total REAL NOT NULL DEFAULT 0, placed_at TEXT NOT NULL DEFAULT (datetime('now')));- Add a column
ALTER TABLE customers ADD COLUMN tier TEXT NOT NULL DEFAULT 'standard';- Rename a table
ALTER TABLE customers RENAME TO customers_old;- Drop if it exists
DROP TABLE IF EXISTS temp_results;
Índices
- Index a join key
CREATE INDEX idx_orders_customer_id ON orders (customer_id);- Index if it does not exist yet
CREATE INDEX IF NOT EXISTS idx_orders_placed ON orders (placed_at);- Unique index
CREATE UNIQUE INDEX ux_customers_email ON customers (email);- Expression index
CREATE INDEX idx_customers_email ON customers (lower(email));- Partial index
CREATE INDEX idx_orders_open ON orders (customer_id) WHERE status = 'open';
String functions
- Length and case
SELECT length(name), lower(email), upper(code) FROM customers;- Substring and position
SELECT substr(name, 1, 3), instr(email, '@') FROM customers;- Concatenate with ||
SELECT first_name || ' ' || last_name FROM customers;- Trim and replace
SELECT trim(name), replace(code, '-', '') FROM customers;
Date functions
- Neste momento
SELECT datetime('now'), date('now');- Add and subtract days
SELECT date('now', '-7 day'), date(placed_at, '+1 month') FROM orders;- Recent rows
SELECT * FROM orders WHERE placed_at >= datetime('now', '-30 day');- Format with strftime
SELECT strftime('%Y-%m', placed_at) AS month, sum(total) FROM orders GROUP BY 1;- Difference in days
SELECT julianday('now') - julianday(placed_at) FROM orders;
NULL handling
- Substitute a default
SELECT ifnull(nickname, first_name) FROM customers;- First non-NULL of many
SELECT coalesce(nickname, first_name, 'unknown') FROM customers;- Guard a division by zero
SELECT total / NULLIF(quantity, 0) FROM orders;- Test for NULL (= NULL never matches)
SELECT * FROM customers WHERE deleted_at IS NULL;
Paging
- Page 3, 10 rows per page
SELECT * FROM orders ORDER BY placed_at DESC LIMIT 10 OFFSET 20;- Fast keyset paging with a row value
SELECT * FROM orders WHERE (placed_at, id) < ('2026-01-01', 123) ORDER BY placed_at DESC, id DESC LIMIT 10;
SQLite quirks worth knowing
- Types are a suggestion. Columns have affinity, not enforcement: any column can hold TEXT, INTEGER, REAL, BLOB or NULL.
INTEGER PRIMARY KEYis the rowid alias and gives you a free auto-incrementing key. AddSTRICTafter the closing parenthesis (3.37+) to make types enforced. - Dates are TEXT, REAL or INTEGER. There is no date storage class (a column declared DATETIME just gets NUMERIC affinity); store ISO-8601 text and use
date(),datetime()estrftime()to compute on it. - LIKE is case-insensitive for ASCII.
GLOBis the case-sensitive, wildcard-with-*cousin. - Upserts look like Postgres.
INSERT … ON CONFLICT (sku) DO UPDATE SET …, or the olderINSERT OR REPLACE, which deletes and re-inserts the row. - JOIN support grew late. FULL OUTER and RIGHT JOIN need SQLite 3.39 or newer; older files are INNER/LEFT/CROSS only.
Other SQL cheat sheets
To run this sheet against a live database, get the SQLly desktop app for SQLite, ou explore todos os recursos.
SQLite cheat sheet FAQ
How do I limit rows in SQLite?
Append LIMIT 10, and OFFSET 20 to skip rows. There is no TOP and no FETCH FIRST.
How do I get the ID of the row I just inserted?
Add RETURNING id to the INSERT (SQLite 3.35 and newer), or call SELECT last_insert_rowid(); on the same connection right after it. A column declared INTEGER PRIMARY KEY is an alias for the rowid, so it fills itself in when you leave it out.
Do I need AUTOINCREMENT?
Usually no. INTEGER PRIMARY KEY already assigns the next rowid. The AUTOINCREMENT keyword additionally forbids reusing ids of deleted rows, at a small cost; use it only when ids must never be reused.
Is the database really just a file?
Yes. One file holds the whole database, which is why SQLite is everywhere from phones to browsers. Open it with the sqlite3 command line or SQLly. Turn on WAL mode with PRAGMA journal_mode = WAL; so readers keep working while one writer commits; SQLite still allows only one writer at a time.
Run these against your own database
SQLly is a native SQL workbench for macOS, Windows and Linux. It connects to all five engines on these sheets, and its IntelliSense completes from your real schema.