{"id":"sql-cheat-sheets/mysql","corpus":"sql-cheat-sheets","engine":"mysql","language":"en","title":"MySQL cheat sheet","description":"MySQL cheat sheet: LIMIT, joins, AUTO_INCREMENT, INSERT IGNORE, ON DUPLICATE KEY UPDATE, GROUP_CONCAT, date functions, backticks and the utf8mb4 gotchas.","body":{"slug":"mysql","name":"MySQL","h1":"MySQL cheat sheet","lede":"Everyday MySQL in the syntax MySQL 8.0 and 8.4 accept: backticked names, AUTO_INCREMENT, ON DUPLICATE KEY UPDATE and utf8mb4. MariaDB runs most of it; the row-alias upsert and functional indexes are MySQL-only.","quirks_html":["<strong>Identifiers get backticks.</strong> <code>`order`</code> and <code>`group`</code> are quoted names because they are reserved words. In the default SQL mode double quotes are strings, not identifiers.","<strong>Row counts use LIMIT.</strong> <code>LIMIT 10 OFFSET 20</code>, or the shorter <code>LIMIT 20, 10</code>. There is no TOP and no OFFSET/FETCH.","<strong>Keys are AUTO_INCREMENT.</strong> Declare an integer key <code>AUTO_INCREMENT</code> and MySQL fills it in; read back the new value with <code>LAST_INSERT_ID()</code> on the same connection.","<strong>Case sensitivity lives in the collation.</strong> String comparison and <code>LIKE</code> are case-insensitive under the default utf8mb4 collations; <code>COLLATE utf8mb4_bin</code> or a <code>_cs</code> collation forces exact matching.","<strong>utf8mb4, not utf8.</strong> MySQL's <code>utf8</code> charset stores only three bytes and cannot hold every character; new tables use <code>CHARACTER SET utf8mb4</code>."],"sections":[{"heading":"SELECT basics","rows":[{"what":"Everything from a table","sql":"SELECT * FROM customers;","note":null,"related_path":null},{"what":"First 10 rows, ordered","sql":"SELECT * FROM customers ORDER BY last_name LIMIT 10;","note":null,"related_path":null},{"what":"Expression with an alias","sql":"SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM customers;","note":null,"related_path":null},{"what":"Unique values","sql":"SELECT DISTINCT country FROM customers;","note":null,"related_path":null},{"what":"Quote a name that is a reserved word","sql":"SELECT `order`, `status` FROM jobs;","note":null,"related_path":null}],"id":"s-select-basics"},{"heading":"Joins","rows":[{"what":"Inner join","sql":"SELECT o.id, c.name FROM orders o JOIN customers c ON o.customer_id = c.id;","note":null,"related_path":null},{"what":"Left join keeps unmatched rows","sql":"SELECT c.name, o.id FROM customers c LEFT JOIN orders o ON o.customer_id = c.id;","note":null,"related_path":null},{"what":"Join on equal column names with USING","sql":"SELECT i.order_id, s.shipped_at FROM order_items i JOIN shipments s USING (order_id);","note":null,"related_path":null},{"what":"Self join","sql":"SELECT e.name, manager.name FROM employees e JOIN employees manager ON manager.id = e.manager_id;","note":null,"related_path":null}],"id":"s-joins"},{"heading":"Filtering","rows":[{"what":"Combined conditions","sql":"SELECT * FROM orders WHERE country = 'DE' AND placed_at >= '2026-01-01';","note":null,"related_path":null},{"what":"Range and lists","sql":"SELECT * FROM orders WHERE total BETWEEN 100 AND 500 AND status IN ('new', 'paid');","note":null,"related_path":null},{"what":"Pattern match","sql":"SELECT * FROM customers WHERE name LIKE 'A%' AND name NOT LIKE '%test%';","note":null,"related_path":null},{"what":"Full-text search","sql":"SELECT * FROM products WHERE MATCH (name, description) AGAINST ('laptop');","note":null,"related_path":null},{"what":"Exists elsewhere","sql":"SELECT * FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);","note":null,"related_path":null}],"id":"s-filtering"},{"heading":"Aggregation","rows":[{"what":"Count per group","sql":"SELECT country, COUNT(*) AS customers FROM customers GROUP BY country;","note":null,"related_path":null},{"what":"Groups after filtering with HAVING","sql":"SELECT customer_id, SUM(total) AS spent FROM orders GROUP BY customer_id HAVING SUM(total) > 1000;","note":null,"related_path":null},{"what":"Aggregate text with GROUP_CONCAT","sql":"SELECT country, GROUP_CONCAT(name ORDER BY name SEPARATOR ', ') FROM customers GROUP BY country;","note":null,"related_path":null},{"what":"Rank within a partition","sql":"SELECT name, department, RANK() OVER (PARTITION BY department ORDER BY salary DESC) FROM employees;","note":null,"related_path":null},{"what":"Every selected column must be grouped","sql":"SELECT country, status, COUNT(*) FROM orders GROUP BY country, status;","note":null,"related_path":null}],"id":"s-aggregation"},{"heading":"Insert, update, delete","rows":[{"what":"Single and multi-row insert","sql":"INSERT INTO customers (first_name, last_name) VALUES ('Ada', 'Lovelace'), ('Grace', 'Hopper');","note":null,"related_path":null},{"what":"Insert or skip duplicates","sql":"INSERT IGNORE INTO subscribers (email) VALUES ('ada@example.com');","note":null,"related_path":null},{"what":"Upsert with ON DUPLICATE KEY UPDATE (row alias: 8.0.19+)","sql":"INSERT INTO stock (sku, count) VALUES ('A1', 5) AS new ON DUPLICATE KEY UPDATE count = stock.count + new.count;","note":null,"related_path":null},{"what":"Update through a join","sql":"UPDATE customers c JOIN totals t ON t.customer_id = c.id SET c.tier = 'gold' WHERE t.spent >= 1000;","note":null,"related_path":null},{"what":"Delete in batches","sql":"DELETE FROM audit_events WHERE archived = 1 LIMIT 100;","note":null,"related_path":null}],"id":"s-insert-update-delete"},{"heading":"Create, alter, drop","rows":[{"what":"Create a table","sql":"CREATE TABLE orders (id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, customer_id BIGINT UNSIGNED NOT NULL, total DECIMAL(10,2) NOT NULL DEFAULT 0, placed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;","note":null,"related_path":"/sql-ddl/create-table"},{"what":"Add a column","sql":"ALTER TABLE customers ADD COLUMN tier VARCHAR(20) NOT NULL DEFAULT 'standard';","note":"MySQL 8.0.12+ adds a trailing column as INSTANT with no rebuild; other shapes copy the table.","related_path":"/sql-ddl/alter-table-add-column"},{"what":"Add a column at a position","sql":"ALTER TABLE customers ADD COLUMN tier VARCHAR(20) NOT NULL DEFAULT 'standard' AFTER last_name;","note":"FIRST or AFTER places the column where the other engines always append; MySQL 8.0.29+ manages that as an INSTANT change too.","related_path":"/sql-ddl/alter-table-add-column"},{"what":"Change a column type","sql":"ALTER TABLE customers MODIFY COLUMN tier VARCHAR(40) NOT NULL DEFAULT 'standard';","note":"MODIFY redefines the column in place, CHANGE also renames it, and MySQL's ALTER COLUMN only sets or drops a DEFAULT.","related_path":"/sql-ddl/alter-table-alter-column"},{"what":"Drop a column","sql":"ALTER TABLE customers DROP COLUMN tier;","note":"The column also leaves every index that contains it, and MySQL drops an index left without any columns.","related_path":"/sql-ddl/alter-table-drop-column"},{"what":"Rename a table","sql":"RENAME TABLE customers TO customers_old, customers_new TO customers;","note":"The renames run left to right inside one atomic statement, so no other session ever sees a missing name.","related_path":"/sql-ddl/rename-table"},{"what":"Create a table from a query","sql":"CREATE TABLE big_spenders AS SELECT customer_id, SUM(total) AS spent FROM orders GROUP BY customer_id HAVING SUM(total) > 1000;","note":"Only the data moves: recreate indexes and constraints afterwards, or use CREATE TABLE big_spenders LIKE orders for an empty structural copy.","related_path":"/sql-ddl/create-table-as"},{"what":"Truncate a table","sql":"TRUNCATE TABLE orders;","note":"MySQL commits DDL implicitly, so a surrounding transaction cannot roll it back; the AUTO_INCREMENT counter resets.","related_path":"/sql-ddl/truncate-table"},{"what":"Temporary table","sql":"CREATE TEMPORARY TABLE stage (id BIGINT PRIMARY KEY, email VARCHAR(320));","note":"The table is visible only to the creating session, can shadow a permanent table of the same name, and takes no foreign keys.","related_path":"/sql-ddl/temp-tables"},{"what":"Drop if it exists","sql":"DROP TABLE IF EXISTS temp_results;","note":null,"related_path":"/sql-ddl/drop-table"}],"id":"s-create-alter-drop"},{"heading":"Indexes","rows":[{"what":"Index a join key","sql":"CREATE INDEX idx_orders_customer_id ON orders (customer_id);","note":null,"related_path":"/sql-ddl/create-index"},{"what":"Composite index","sql":"CREATE INDEX idx_orders_placed ON orders (placed_at DESC, customer_id);","note":null,"related_path":null},{"what":"Unique index","sql":"CREATE UNIQUE INDEX ux_customers_email ON customers (email);","note":null,"related_path":null},{"what":"Full-text index","sql":"CREATE FULLTEXT INDEX ft_products_text ON products (name, description);","note":null,"related_path":null},{"what":"Functional index (8.0.13+, note the double parentheses)","sql":"CREATE INDEX idx_users_email_lc ON users ((LOWER(email)));","note":null,"related_path":null},{"what":"Drop an index","sql":"DROP INDEX idx_orders_customer_id ON orders;","note":"MySQL has no IF EXISTS for indexes, so check information_schema.statistics first when the index may be missing.","related_path":"/sql-ddl/drop-index"}],"id":"s-indexes"},{"heading":"Views","rows":[{"what":"Create a view","sql":"CREATE VIEW open_orders AS\nSELECT id, customer_id, total\nFROM orders WHERE status = 'open';","note":null,"related_path":"/sql-ddl/create-view"},{"what":"Guard writes through the view","sql":"CREATE OR REPLACE VIEW open_orders AS\nSELECT id, customer_id, total\nFROM orders WHERE status = 'open'\nWITH CHECK OPTION;","note":"OR REPLACE swaps the definition; WITH CHECK OPTION rejects writes that would move a row out of the view.","related_path":"/sql-ddl/create-view"},{"what":"Change a view","sql":"ALTER VIEW open_orders AS\nSELECT id, customer_id, total\nFROM orders WHERE status IN ('open', 'processing');","note":"ALTER VIEW ... AS redefines the query, the same as CREATE OR REPLACE.","related_path":"/sql-ddl/alter-view"},{"what":"Drop several views","sql":"DROP VIEW IF EXISTS v_tmp1, v_tmp2;","note":"MySQL warns for each missing name instead of failing, so this is a tidy closer for migration scripts.","related_path":"/sql-ddl/drop-view"}],"id":"s-views"},{"heading":"String functions","rows":[{"what":"Length and case","sql":"SELECT CHAR_LENGTH(name), LOWER(email), UPPER(code) FROM customers;","note":null,"related_path":null},{"what":"Substring and position","sql":"SELECT SUBSTRING(name, 1, 3), LOCATE('@', email) FROM customers;","note":null,"related_path":null},{"what":"Concatenate","sql":"SELECT CONCAT(first_name, ' ', last_name) FROM customers;","note":null,"related_path":null},{"what":"Trim and replace","sql":"SELECT TRIM(name), REPLACE(code, '-', '') FROM customers;","note":null,"related_path":null}],"id":"s-string-functions"},{"heading":"Date functions","rows":[{"what":"Right now","sql":"SELECT NOW(), CURDATE();","note":null,"related_path":null},{"what":"Subtract an interval","sql":"SELECT DATE_SUB(NOW(), INTERVAL 7 DAY);","note":null,"related_path":null},{"what":"Recent rows","sql":"SELECT * FROM orders WHERE placed_at >= NOW() - INTERVAL 30 DAY;","note":null,"related_path":null},{"what":"Difference in days","sql":"SELECT DATEDIFF(NOW(), placed_at) FROM orders;","note":null,"related_path":null},{"what":"Format and extract","sql":"SELECT DATE_FORMAT(placed_at, '%Y-%m-%d'), EXTRACT(YEAR FROM placed_at) FROM orders;","note":null,"related_path":null}],"id":"s-date-functions"},{"heading":"NULL handling","rows":[{"what":"Substitute a default","sql":"SELECT IFNULL(nickname, first_name) FROM customers;","note":null,"related_path":null},{"what":"First non-NULL of many","sql":"SELECT COALESCE(nickname, first_name, 'unknown') FROM customers;","note":null,"related_path":null},{"what":"Guard a division by zero","sql":"SELECT total / NULLIF(quantity, 0) FROM orders;","note":null,"related_path":null},{"what":"Null-safe equality (NULL <=> NULL is 1)","sql":"SELECT * FROM products p JOIN supplies s ON s.sku = p.sku WHERE NOT (p.price <=> s.price);","note":null,"related_path":null}],"id":"s-null-handling"},{"heading":"Paging","rows":[{"what":"Page 3, 10 rows per page","sql":"SELECT * FROM orders ORDER BY placed_at DESC LIMIT 10 OFFSET 20;","note":null,"related_path":null},{"what":"Shorter LIMIT offset, count form","sql":"SELECT * FROM orders ORDER BY placed_at DESC LIMIT 20, 10;","note":null,"related_path":null}],"id":"s-paging"}],"faqs":[{"question":"How do I limit rows in MySQL?","answer":"Append LIMIT 10, and OFFSET 20 to skip rows; LIMIT 20, 10 is the same thing in offset-then-count order. TOP and FETCH FIRST are other engines' syntax."},{"question":"How do I get the ID of the row I just inserted?","answer":"Call LAST_INSERT_ID() on the same connection right after the INSERT. It returns the first auto-generated key of the statement, even for a multi-row insert."},{"question":"Why is my WHERE comparison case-insensitive?","answer":"The default utf8mb4 collations compare case-insensitively, so 'ada' = 'Ada'. Write WHERE name COLLATE utf8mb4_bin = 'Ada', or declare the column with a binary or _cs collation when it matters. Database and table names are a separate matter: they map to files, so they are case-sensitive on Linux by default (lower_case_table_names = 0). Column names are never case-sensitive."},{"question":"Should I use utf8 or utf8mb4?","answer":"utf8mb4. MySQL's utf8 is an alias for utf8mb3, which stores at most three bytes per character and cannot hold anything outside the Basic Multilingual Plane, emoji included. utf8mb4 is the default from MySQL 8.0, with utf8mb4_0900_ai_ci as its default collation; older schemas often still carry utf8mb3 columns."}]},"source_url":"https://sqlly.app/sql-cheat-sheets/mysql","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-cheat-sheets/oracle","corpus":"sql-cheat-sheets","engine":"oracle","language":"en","title":"Oracle cheat sheet","description":"Oracle cheat sheet: FETCH FIRST, ROWNUM, dual, sequences, LISTAGG, TO_CHAR and TO_DATE, NVL, MERGE, and the empty string that is really NULL.","body":{"slug":"oracle","name":"Oracle","h1":"Oracle cheat sheet","lede":"Everyday Oracle SQL in the dialect Oracle speaks, not the one the other engines share: dual, sequences, FETCH FIRST, LISTAGG and TO_CHAR.","quirks_html":["<strong>Selects needed a table, so there is dual.</strong> <code>SELECT SYSDATE FROM dual;</code> evaluates an expression without data. Oracle 23ai finally allows <code>SELECT SYSDATE;</code> with no FROM, but code that must run on 19c still needs dual.","<strong>Row counts use FETCH FIRST or ROWNUM.</strong> <code>FETCH FIRST 10 ROWS ONLY</code> (12c and newer) or the older <code>ROWNUM</code> in a subquery. There is no LIMIT.","<strong>The empty string is NULL.</strong> <code>''</code> compares as NULL in Oracle, so <code>NVL</code> and <code>IS NULL</code> see them the same way.","<strong>DATE has a time.</strong> An Oracle <code>DATE</code> stores year to second; <code>TIMESTAMP</code> adds fractional seconds. Convert explicitly with <code>TO_CHAR</code> and <code>TO_DATE</code>.","<strong>Names fold to uppercase.</strong> Unquoted identifiers become uppercase, the mirror image of PostgreSQL folding them to lowercase; quoted <code>\"MixedCase\"</code> keeps its case forever."],"sections":[{"heading":"SELECT basics","rows":[{"what":"Everything from a table","sql":"SELECT * FROM customers;","note":null,"related_path":null},{"what":"First 10 rows, ordered","sql":"SELECT * FROM customers ORDER BY last_name FETCH FIRST 10 ROWS ONLY;","note":null,"related_path":null},{"what":"Evaluate an expression without a table","sql":"SELECT SYSDATE, 1 + 1 FROM dual;","note":null,"related_path":null},{"what":"Expression with an alias","sql":"SELECT first_name || ' ' || last_name AS full_name FROM customers;","note":null,"related_path":null},{"what":"Unique values","sql":"SELECT DISTINCT country FROM customers;","note":null,"related_path":null}],"id":"s-select-basics"},{"heading":"Joins","rows":[{"what":"Inner join","sql":"SELECT o.id, c.name FROM orders o JOIN customers c ON o.customer_id = c.id;","note":null,"related_path":null},{"what":"Left join keeps unmatched rows","sql":"SELECT c.name, o.id FROM customers c LEFT JOIN orders o ON o.customer_id = c.id;","note":null,"related_path":null},{"what":"Both sides, matched or not","sql":"SELECT e.name, m.name FROM employees e FULL OUTER JOIN managers m ON m.employee_id = e.id;","note":null,"related_path":null},{"what":"Old-style outer join: (+) marks the optional side","sql":"SELECT c.name, o.id FROM customers c, orders o WHERE o.customer_id (+) = c.id;","note":null,"related_path":null}],"id":"s-joins"},{"heading":"Filtering","rows":[{"what":"Combined conditions","sql":"SELECT * FROM orders WHERE country = 'DE' AND placed_at >= DATE '2026-01-01';","note":null,"related_path":null},{"what":"Range and lists","sql":"SELECT * FROM orders WHERE total BETWEEN 100 AND 500 AND status IN ('new', 'paid');","note":null,"related_path":null},{"what":"Pattern match","sql":"SELECT * FROM customers WHERE name LIKE 'A%' AND name NOT LIKE '%test%';","note":null,"related_path":null},{"what":"Exists elsewhere","sql":"SELECT * FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);","note":null,"related_path":null}],"id":"s-filtering"},{"heading":"Aggregation","rows":[{"what":"Count per group","sql":"SELECT country, COUNT(*) AS customers FROM customers GROUP BY country;","note":null,"related_path":null},{"what":"Groups after filtering with HAVING","sql":"SELECT customer_id, SUM(total) AS spent FROM orders GROUP BY customer_id HAVING SUM(total) > 1000;","note":null,"related_path":null},{"what":"Aggregate text with LISTAGG","sql":"SELECT country, LISTAGG(name, ', ') WITHIN GROUP (ORDER BY name) FROM customers GROUP BY country;","note":null,"related_path":null},{"what":"Rank within a partition","sql":"SELECT name, department, RANK() OVER (PARTITION BY department ORDER BY salary DESC) FROM employees;","note":null,"related_path":null}],"id":"s-aggregation"},{"heading":"Insert, update, delete","rows":[{"what":"Insert with a sequence key","sql":"INSERT INTO orders (id, customer_id, total) VALUES (orders_seq.NEXTVAL, 42, 99.90);","note":null,"related_path":null},{"what":"Update with a subquery","sql":"UPDATE customers SET tier = 'gold' WHERE id IN (SELECT customer_id FROM totals WHERE spent >= 1000);","note":null,"related_path":null},{"what":"Delete a bounded batch","sql":"DELETE FROM audit_events WHERE archived = 1 AND ROWNUM <= 100;","note":null,"related_path":null},{"what":"Upsert with MERGE","sql":"MERGE INTO targets t USING sources s ON (t.id = s.id) WHEN MATCHED THEN UPDATE SET t.name = s.name WHEN NOT MATCHED THEN INSERT (id, name) VALUES (s.id, s.name);","note":null,"related_path":null}],"id":"s-insert-update-delete"},{"heading":"Create, alter, drop","rows":[{"what":"Create a table","sql":"CREATE TABLE orders (id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, customer_id NUMBER NOT NULL REFERENCES customers (id), total NUMBER(10,2) DEFAULT 0 NOT NULL, placed_at DATE DEFAULT SYSDATE NOT NULL);","note":null,"related_path":"/sql-ddl/create-table"},{"what":"Create only if missing","sql":"BEGIN\n  EXECUTE IMMEDIATE 'CREATE TABLE tmp_x (id NUMBER PRIMARY KEY)';\nEXCEPTION WHEN OTHERS THEN IF SQLCODE != -955 THEN RAISE; END IF;\nEND;\n/","note":"CREATE TABLE has no IF NOT EXISTS on Oracle: ORA-00955 means the name is taken, and only the DROP family gained IF EXISTS in 23ai.","related_path":"/sql-ddl/create-table"},{"what":"Add a column","sql":"ALTER TABLE customers ADD (tier VARCHAR2(20) DEFAULT 'standard' NOT NULL);","note":"Since 12.1 Oracle turns a NOT NULL add with a constant DEFAULT into a dictionary-only change, so the table size does not drive the cost.","related_path":"/sql-ddl/alter-table-add-column"},{"what":"Change a column type","sql":"ALTER TABLE customers MODIFY (tier VARCHAR2(40));","note":"Oracle grows a VARCHAR2 freely, but shrinking it or changing the datatype needs the column to hold NULL in every row.","related_path":"/sql-ddl/alter-table-alter-column"},{"what":"Drop a column","sql":"ALTER TABLE customers SET UNUSED COLUMN tier;\nALTER TABLE customers DROP UNUSED COLUMNS;","note":"SET UNUSED hides the column instantly in the dictionary, and DROP UNUSED COLUMNS reclaims the space later, ideally off-peak.","related_path":"/sql-ddl/alter-table-drop-column"},{"what":"Rename a table","sql":"RENAME orders TO orders_2025;","note":"Oracle marks dependent views and procedures invalid, and they recompile against the new name the next time they run.","related_path":"/sql-ddl/rename-table"},{"what":"Rename a column","sql":"ALTER TABLE customers RENAME COLUMN name TO full_name;","note":"Dependent objects stay valid and pick up the new column name on their next use.","related_path":null},{"what":"Truncate a table","sql":"TRUNCATE TABLE temp_results DROP STORAGE;","note":"Oracle commits implicitly around it and no sequence moves, so the statement cannot be rolled back.","related_path":"/sql-ddl/truncate-table"},{"what":"Global temporary table","sql":"CREATE GLOBAL TEMPORARY TABLE stage (id NUMBER PRIMARY KEY) ON COMMIT PRESERVE ROWS;","note":"The definition is permanent and shared; only the rows are temporary, kept per session under PRESERVE ROWS or cleared at commit under DELETE ROWS.","related_path":"/sql-ddl/temp-tables"},{"what":"Create a table from a query","sql":"CREATE TABLE big_spenders AS SELECT customer_id, SUM(total) AS spent FROM orders GROUP BY customer_id HAVING SUM(total) > 1000;","note":"Only data and NOT NULL flags move: constraints and indexes need recreating, and the statement commits implicitly.","related_path":"/sql-ddl/create-table-as"},{"what":"Drop, skipping the recycle bin","sql":"DROP TABLE temp_results PURGE;","note":"Without PURGE Oracle moves the table to the recycle bin, and FLASHBACK TABLE ... TO BEFORE DROP restores it while it stays there.","related_path":"/sql-ddl/drop-table"},{"what":"Drop if it exists (23ai+)","sql":"DROP TABLE IF EXISTS temp_results;","note":null,"related_path":"/sql-ddl/drop-table"}],"id":"s-create-alter-drop"},{"heading":"Indexes","rows":[{"what":"Index a join key","sql":"CREATE INDEX idx_orders_customer_id ON orders (customer_id);","note":null,"related_path":"/sql-ddl/create-index"},{"what":"Composite index","sql":"CREATE INDEX idx_orders_placed ON orders (placed_at DESC, customer_id);","note":null,"related_path":null},{"what":"Unique index","sql":"CREATE UNIQUE INDEX ux_customers_email ON customers (email);","note":null,"related_path":null},{"what":"Function-based index","sql":"CREATE INDEX idx_customers_email ON customers (UPPER(email));","note":"The optimizer uses it only when the query spells the same expression and the index has statistics.","related_path":"/sql-ddl/create-index"},{"what":"Drop an index","sql":"DROP INDEX IF EXISTS ux_customers_email;","note":"IF EXISTS arrived with Oracle 23ai's other DROP forms; older servers raise ORA-01418 when the index is missing.","related_path":"/sql-ddl/drop-index"}],"id":"s-indexes"},{"heading":"Views","rows":[{"what":"Create a view","sql":"CREATE VIEW open_orders AS\nSELECT id, customer_id, total\nFROM orders WHERE status = 'open';","note":null,"related_path":"/sql-ddl/create-view"},{"what":"Redefine a view","sql":"CREATE OR REPLACE VIEW open_orders AS\nSELECT id, customer_id, total\nFROM orders WHERE status IN ('open', 'processing');","note":"OR REPLACE redefines in place and keeps grants; FORCE creates the view even while base objects are missing.","related_path":"/sql-ddl/create-view"},{"what":"Recompile a view","sql":"ALTER VIEW open_orders COMPILE;","note":"ALTER VIEW never changes the query: it revalidates the stored definition after base-object changes.","related_path":"/sql-ddl/alter-view"},{"what":"Drop a view","sql":"DROP VIEW open_orders;","note":"IF EXISTS works from Oracle 23c on; older servers raise ORA-00942 when the view is missing.","related_path":"/sql-ddl/drop-view"}],"id":"s-views"},{"heading":"String functions","rows":[{"what":"Length and case","sql":"SELECT LENGTH(name), LOWER(email), UPPER(code) FROM customers;","note":null,"related_path":null},{"what":"Substring and position","sql":"SELECT SUBSTR(name, 1, 3), INSTR(email, '@') FROM customers;","note":null,"related_path":null},{"what":"Concatenate with ||","sql":"SELECT first_name || ' ' || last_name FROM customers;","note":null,"related_path":null},{"what":"Pad and trim","sql":"SELECT LPAD(id, 6, '0'), TRIM(name) FROM customers;","note":null,"related_path":null},{"what":"Replace","sql":"SELECT REPLACE(code, '-', '') FROM customers;","note":null,"related_path":null}],"id":"s-string-functions"},{"heading":"Date functions","rows":[{"what":"Right now","sql":"SELECT SYSDATE, SYSTIMESTAMP FROM dual;","note":null,"related_path":null},{"what":"Add months","sql":"SELECT ADD_MONTHS(SYSDATE, -3) FROM dual;","note":null,"related_path":null},{"what":"Truncate to a month","sql":"SELECT TRUNC(placed_at, 'MM') AS month, SUM(total) FROM orders GROUP BY TRUNC(placed_at, 'MM');","note":null,"related_path":null},{"what":"Format a date","sql":"SELECT TO_CHAR(placed_at, 'YYYY-MM-DD') FROM orders;","note":null,"related_path":null},{"what":"Parse a date safely","sql":"SELECT * FROM orders WHERE placed_at >= TO_DATE('2026-01-01', 'YYYY-MM-DD');","note":null,"related_path":null},{"what":"Months between two dates","sql":"SELECT MONTHS_BETWEEN(SYSDATE, placed_at) FROM orders;","note":null,"related_path":null}],"id":"s-date-functions"},{"heading":"NULL handling","rows":[{"what":"Substitute a default","sql":"SELECT NVL(nickname, first_name) FROM customers;","note":null,"related_path":null},{"what":"Two outcomes with NVL2","sql":"SELECT NVL2(phone, 'has phone', 'no phone') FROM customers;","note":null,"related_path":null},{"what":"First non-NULL of many","sql":"SELECT COALESCE(nickname, first_name, 'unknown') FROM customers;","note":null,"related_path":null},{"what":"The empty string is NULL","sql":"SELECT * FROM tasks WHERE note IS NULL;","note":null,"related_path":null}],"id":"s-null-handling"},{"heading":"Paging","rows":[{"what":"Page 3, 10 rows per page (12c+)","sql":"SELECT * FROM orders ORDER BY placed_at DESC OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;","note":null,"related_path":null},{"what":"Top N before 12c with ROWNUM","sql":"SELECT * FROM (SELECT * FROM customers ORDER BY last_name) WHERE ROWNUM <= 10;","note":null,"related_path":null}],"id":"s-paging"}],"faqs":[{"question":"How do I limit rows in Oracle?","answer":"Since 12c, append FETCH FIRST 10 ROWS ONLY (and OFFSET n ROWS before it for paging). On older releases, wrap the ordered query in a subquery and filter WHERE ROWNUM <= 10 on the outside."},{"question":"What is the dual table?","answer":"A one-row, one-column table every Oracle database ships, used when an expression needs a FROM clause: SELECT SYSDATE FROM dual;. SQL Server, PostgreSQL, MySQL and SQLite let you omit FROM, and so does Oracle from 23ai; dual still works there."},{"question":"Why does '' behave like NULL?","answer":"Oracle treats a zero-length string as NULL, so note = '' never matches and NVL(note, 'x') fills in empty strings too. If you come from SQL Server or PostgreSQL, that is the single biggest Oracle surprise."},{"question":"How do I get the key of a row I just inserted?","answer":"In PL/SQL, add RETURNING id INTO a variable to the INSERT. With an explicit sequence, orders_seq.CURRVAL returns the value this session just drew with NEXTVAL. An IDENTITY column is backed by a system-generated sequence, so RETURNING is the simplest way to read it."}]},"source_url":"https://sqlly.app/sql-cheat-sheets/oracle","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-cheat-sheets/postgresql","corpus":"sql-cheat-sheets","engine":"postgresql","language":"en","title":"PostgreSQL cheat sheet","description":"PostgreSQL cheat sheet: LIMIT and OFFSET, joins, RETURNING, ON CONFLICT upserts, ::casts, FILTER, date_trunc, string_agg and the quoting rules that bite everyone once.","body":{"slug":"postgresql","name":"PostgreSQL","h1":"PostgreSQL cheat sheet","lede":"Everyday Postgres in PostgreSQL's own syntax, including the shortcuts other engines make you work around: RETURNING, ON CONFLICT, :: casts and FILTER.","quirks_html":["<strong>Unquoted names fold to lowercase.</strong> <code>MyTable</code> becomes <code>mytable</code>; to keep mixed case you must quote it as <code>\"MyTable\"</code> forever. Double quotes are identifiers; single quotes are strings.","<strong>INSERT can give the row back.</strong> <code>RETURNING id</code> (or <code>RETURNING *</code>) returns the inserted or updated rows, so no second round-trip for generated keys.","<strong>Upserts are ON CONFLICT.</strong> <code>INSERT … ON CONFLICT (sku) DO UPDATE SET …</code> with <code>EXCLUDED</code> for the rejected row's values.","<strong>Casts are two colons.</strong> <code>created_at::date</code>, <code>'7'::int</code>; and <code>ILIKE</code> is the case-insensitive <code>LIKE</code>.","<strong>Aggregates take a FILTER.</strong> <code>COUNT(*) FILTER (WHERE active)</code> replaces the conditional CASE inside every aggregate."],"sections":[{"heading":"SELECT basics","rows":[{"what":"Everything from a table","sql":"SELECT * FROM customers;","note":null,"related_path":null},{"what":"First 10 rows, ordered","sql":"SELECT * FROM customers ORDER BY last_name LIMIT 10;","note":null,"related_path":null},{"what":"Expression with an alias and a cast","sql":"SELECT first_name || ' ' || last_name AS full_name, created_at::date FROM customers;","note":null,"related_path":null},{"what":"Unique values","sql":"SELECT DISTINCT country FROM customers;","note":null,"related_path":null},{"what":"First row per group","sql":"SELECT DISTINCT ON (customer_id) customer_id, placed_at FROM orders ORDER BY customer_id, placed_at DESC;","note":null,"related_path":null}],"id":"s-select-basics"},{"heading":"Joins","rows":[{"what":"Inner join","sql":"SELECT o.id, c.name FROM orders o JOIN customers c ON o.customer_id = c.id;","note":null,"related_path":null},{"what":"Left join keeps unmatched rows","sql":"SELECT c.name, o.id FROM customers c LEFT JOIN orders o ON o.customer_id = c.id;","note":null,"related_path":null},{"what":"Both sides, matched or not","sql":"SELECT e.name, m.name FROM employees e FULL OUTER JOIN managers m ON m.employee_id = e.id;","note":null,"related_path":null},{"what":"Join on equal column names with USING","sql":"SELECT i.order_id, s.shipped_at FROM order_items i JOIN shipments s USING (order_id);","note":null,"related_path":null},{"what":"Lateral join per row","sql":"SELECT c.name, recent.placed_at FROM customers c CROSS JOIN LATERAL (SELECT placed_at FROM orders o WHERE o.customer_id = c.id ORDER BY placed_at DESC LIMIT 3) recent;","note":null,"related_path":null}],"id":"s-joins"},{"heading":"Filtering","rows":[{"what":"Combined conditions","sql":"SELECT * FROM orders WHERE country = 'DE' AND placed_at >= '2026-01-01';","note":null,"related_path":null},{"what":"Case-insensitive pattern match","sql":"SELECT * FROM customers WHERE name ILIKE 'ada%';","note":null,"related_path":null},{"what":"Range and lists","sql":"SELECT * FROM orders WHERE total BETWEEN 100 AND 500 AND status IN ('new', 'paid');","note":null,"related_path":null},{"what":"Exists elsewhere","sql":"SELECT * FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);","note":null,"related_path":null},{"what":"Array membership","sql":"SELECT * FROM orders WHERE 'vip' = ANY (tags);","note":null,"related_path":null}],"id":"s-filtering"},{"heading":"Aggregation","rows":[{"what":"Count per group","sql":"SELECT country, COUNT(*) AS customers FROM customers GROUP BY country;","note":null,"related_path":null},{"what":"Groups after filtering with HAVING","sql":"SELECT customer_id, SUM(total) AS spent FROM orders GROUP BY customer_id HAVING SUM(total) > 1000;","note":null,"related_path":null},{"what":"Conditional aggregates with FILTER","sql":"SELECT department, COUNT(*) FILTER (WHERE active) AS active_count FROM employees GROUP BY department;","note":null,"related_path":null},{"what":"Rank within a partition","sql":"SELECT name, department, RANK() OVER (PARTITION BY department ORDER BY salary DESC) FROM employees;","note":null,"related_path":null},{"what":"Aggregate text with string_agg","sql":"SELECT country, string_agg(name, ', ' ORDER BY name) FROM customers GROUP BY country;","note":null,"related_path":null}],"id":"s-aggregation"},{"heading":"Insert, update, delete","rows":[{"what":"Insert and read back the key","sql":"INSERT INTO customers (first_name, last_name) VALUES ('Ada', 'Lovelace') RETURNING id;","note":null,"related_path":null},{"what":"Upsert with ON CONFLICT","sql":"INSERT INTO stock (sku, count) VALUES ('A1', 5) ON CONFLICT (sku) DO UPDATE SET count = stock.count + EXCLUDED.count;","note":null,"related_path":null},{"what":"Insert or do nothing","sql":"INSERT INTO subscribers (email) VALUES ('ada@example.com') ON CONFLICT (email) DO NOTHING;","note":null,"related_path":null},{"what":"Update from another table","sql":"UPDATE products p SET price = s.price FROM supplies s WHERE s.sku = p.sku;","note":null,"related_path":null},{"what":"Delete with a join via USING","sql":"DELETE FROM orders o USING customers c WHERE o.customer_id = c.id AND c.closed;","note":null,"related_path":null}],"id":"s-insert-update-delete"},{"heading":"Create, alter, drop","rows":[{"what":"Create a table","sql":"CREATE TABLE orders (id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, customer_id BIGINT NOT NULL REFERENCES customers (id), total NUMERIC(10,2) NOT NULL DEFAULT 0, placed_at TIMESTAMPTZ NOT NULL DEFAULT now());","note":null,"related_path":"/sql-ddl/create-table"},{"what":"Add a column","sql":"ALTER TABLE customers ADD COLUMN tier text NOT NULL DEFAULT 'standard';","note":"Since PostgreSQL 11 a constant DEFAULT is metadata-only; on 10 and earlier the engine rewrote and locked the whole table.","related_path":"/sql-ddl/alter-table-add-column"},{"what":"Change a column type","sql":"ALTER TABLE customers ALTER COLUMN total TYPE numeric(12,2) USING total::numeric(12,2);","note":"The rewrite takes an ACCESS EXCLUSIVE lock, so set lock_timeout in migration scripts or one long-running query blocks the change.","related_path":"/sql-ddl/alter-table-alter-column"},{"what":"Drop a column","sql":"ALTER TABLE customers DROP COLUMN IF EXISTS tier;","note":"PostgreSQL marks the column invisible and skips the rewrite, so space returns as rows are updated, and dependent objects demand CASCADE or block the drop.","related_path":"/sql-ddl/alter-table-drop-column"},{"what":"Rename a column","sql":"ALTER TABLE customers RENAME COLUMN name TO full_name;","note":"Views and foreign key definitions follow the rename automatically; queries that store the old column name as text do not.","related_path":null},{"what":"Rename a table","sql":"ALTER TABLE orders RENAME TO orders_2025;","note":"PostgreSQL rewrites references in views and constraints to the new name; anything that stored the old name as text stays stale.","related_path":"/sql-ddl/rename-table"},{"what":"Create a table from a query","sql":"CREATE TABLE big_spenders AS SELECT customer_id, SUM(total) AS spent FROM orders GROUP BY customer_id HAVING SUM(total) > 1000;","note":"No constraints, indexes or defaults are copied; CREATE TABLE big_spenders (LIKE orders INCLUDING ALL) gives an empty structural copy instead.","related_path":"/sql-ddl/create-table-as"},{"what":"Truncate a table","sql":"TRUNCATE TABLE orders RESTART IDENTITY;","note":"TRUNCATE is transactional on PostgreSQL and rolls back with the transaction; RESTART IDENTITY is what resets the counters.","related_path":"/sql-ddl/truncate-table"},{"what":"Temporary table","sql":"CREATE TEMP TABLE stage (id bigint PRIMARY KEY, payload jsonb) ON COMMIT DROP;","note":"ON COMMIT DROP removes the table at the end of the transaction; without it the table lives in the pg_temp schema until the session closes.","related_path":"/sql-ddl/temp-tables"},{"what":"Drop if it exists","sql":"DROP TABLE IF EXISTS temp_results;","note":null,"related_path":"/sql-ddl/drop-table"}],"id":"s-create-alter-drop"},{"heading":"Indexes","rows":[{"what":"Index a join key","sql":"CREATE INDEX idx_orders_customer_id ON orders (customer_id);","note":null,"related_path":"/sql-ddl/create-index"},{"what":"Index only if missing","sql":"CREATE INDEX IF NOT EXISTS idx_orders_placed ON orders (placed_at);","note":null,"related_path":null},{"what":"Partial index","sql":"CREATE INDEX idx_orders_open ON orders (customer_id) WHERE status = 'open';","note":null,"related_path":null},{"what":"Expression index","sql":"CREATE INDEX idx_customers_email ON customers (lower(email));","note":null,"related_path":null},{"what":"GIN index for JSONB","sql":"CREATE INDEX idx_events_payload ON events USING GIN (payload jsonb_path_ops);","note":null,"related_path":null},{"what":"Build without blocking writes","sql":"CREATE INDEX CONCURRENTLY idx_orders_placed ON orders (placed_at);","note":"A CONCURRENTLY build that fails leaves an INVALID index behind; drop it and run the create again.","related_path":"/sql-ddl/create-index"},{"what":"Drop an index","sql":"DROP INDEX CONCURRENTLY IF EXISTS idx_orders_customer_id;","note":"CONCURRENTLY keeps reads and writes flowing but cannot run inside a transaction block.","related_path":"/sql-ddl/drop-index"}],"id":"s-indexes"},{"heading":"Views","rows":[{"what":"Create a view","sql":"CREATE VIEW open_orders AS\nSELECT id, customer_id, placed_at, total\nFROM orders WHERE status = 'open';","note":null,"related_path":"/sql-ddl/create-view"},{"what":"Redefine a view","sql":"CREATE OR REPLACE VIEW open_orders AS\nSELECT id, customer_id, total\nFROM orders WHERE status = 'open';","note":"OR REPLACE keeps permissions but freezes the existing output columns: names, order and types cannot change, and you may only append new ones.","related_path":"/sql-ddl/create-view"},{"what":"Rename or move a view","sql":"ALTER VIEW open_orders RENAME TO active_orders;","note":"ALTER VIEW handles metadata such as RENAME TO and SET SCHEMA; the query itself only changes through CREATE OR REPLACE.","related_path":"/sql-ddl/alter-view"},{"what":"Drop a view","sql":"DROP VIEW IF EXISTS open_orders;","note":"The default is RESTRICT: the drop fails while another view depends on it, and CASCADE removes the dependents too.","related_path":"/sql-ddl/drop-view"}],"id":"s-views"},{"heading":"String functions","rows":[{"what":"Length and case","sql":"SELECT length(name), lower(email), upper(code) FROM customers;","note":null,"related_path":null},{"what":"Substring and position","sql":"SELECT substring(name FROM 1 FOR 3), position('@' IN email) FROM customers;","note":null,"related_path":null},{"what":"Split on a delimiter","sql":"SELECT split_part(path, '/', 2) FROM links;","note":null,"related_path":null},{"what":"Match a regular expression","sql":"SELECT substring(code FROM '^[0-9]+') FROM items;","note":null,"related_path":null},{"what":"Trim and replace","sql":"SELECT trim(name), replace(code, '-', '') FROM customers;","note":null,"related_path":null}],"id":"s-string-functions"},{"heading":"Date functions","rows":[{"what":"Right now","sql":"SELECT now();","note":null,"related_path":null},{"what":"Intervals","sql":"SELECT now() - interval '7 days';","note":null,"related_path":null},{"what":"Recent rows","sql":"SELECT * FROM orders WHERE placed_at >= now() - interval '30 days';","note":null,"related_path":null},{"what":"Truncate to a month","sql":"SELECT date_trunc('month', placed_at) AS month, sum(total) FROM orders GROUP BY 1;","note":null,"related_path":null},{"what":"Format a timestamp","sql":"SELECT to_char(placed_at, 'YYYY-MM-DD') FROM orders;","note":null,"related_path":null}],"id":"s-date-functions"},{"heading":"NULL handling","rows":[{"what":"Substitute a default","sql":"SELECT coalesce(nickname, first_name, 'unknown') FROM customers;","note":null,"related_path":null},{"what":"Guard a division by zero","sql":"SELECT total / NULLIF(quantity, 0) FROM orders;","note":null,"related_path":null},{"what":"Test for NULL","sql":"SELECT * FROM customers WHERE deleted_at IS NULL;","note":null,"related_path":null},{"what":"Compare two columns, treating NULLs as equal","sql":"SELECT * FROM products p JOIN supplies s ON s.sku = p.sku WHERE p.price IS DISTINCT FROM s.price;","note":null,"related_path":null}],"id":"s-null-handling"},{"heading":"Paging","rows":[{"what":"Page 3, 10 rows per page","sql":"SELECT * FROM orders ORDER BY placed_at DESC LIMIT 10 OFFSET 20;","note":null,"related_path":null},{"what":"Fast keyset paging","sql":"SELECT * FROM orders WHERE (placed_at, id) < ('2026-01-01', 123) ORDER BY placed_at DESC, id DESC LIMIT 10;","note":null,"related_path":null}],"id":"s-paging"}],"faqs":[{"question":"How do I limit rows in PostgreSQL?","answer":"Append LIMIT 10, and OFFSET 20 to skip rows. There is no TOP clause; that is SQL Server syntax."},{"question":"How do I get the ID of the row I just inserted?","answer":"Add RETURNING id (or RETURNING *) to the INSERT. It hands back the generated values without a second query. UPDATE and DELETE accept RETURNING too, and PostgreSQL 18 lets RETURNING name old.* and new.* to see the row before and after the change."},{"question":"Why is my table not found even though I created it?","answer":"PostgreSQL folds unquoted names to lowercase. If you created \"MyTable\" with double quotes, you must always quote it; otherwise PostgreSQL looks for mytable. Prefer lowercase names and you never need quotes."},{"question":"Should I use SERIAL or GENERATED ALWAYS AS IDENTITY?","answer":"Prefer GENERATED ALWAYS AS IDENTITY (or BY DEFAULT when you must insert explicit values). It is the SQL standard form; SERIAL is the older shorthand that ties the column to a sequence you can accidentally desynchronize."}]},"source_url":"https://sqlly.app/sql-cheat-sheets/postgresql","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-cheat-sheets/sql-server","corpus":"sql-cheat-sheets","engine":"sql-server","language":"en","title":"SQL Server cheat sheet (T-SQL)","description":"T-SQL cheat sheet for SQL Server: SELECT with TOP, joins, IDENTITY columns, MERGE, OFFSET/FETCH paging, string and date functions, plus the quirks that trip people up.","body":{"slug":"sql-server","name":"SQL Server","h1":"SQL Server cheat sheet (T-SQL)","lede":"The T-SQL you type against SQL Server and Azure SQL, grouped by task. T-SQL has its own habits for counting rows, joining and typing, so nothing here is pasted from another dialect.","quirks_html":["<strong>Row counts use TOP or OFFSET/FETCH.</strong> <code>LIMIT</code> does not exist in T-SQL: write <code>SELECT TOP (10) …</code> or <code>OFFSET … FETCH NEXT … ROWS ONLY</code> (which requires an <code>ORDER BY</code>).","<strong>Names are bracketed and schema-qualified.</strong> <code>[dbo].[Order Details]</code> is a quoted name (<code>]]</code> escapes a closing bracket). Names, bracketed or not, are case-insensitive under the default collation.","<strong>IDENTITY columns generate keys.</strong> <code>IDENTITY(1,1)</code> is the auto-number, and inserting explicit values needs <code>SET IDENTITY_INSERT … ON</code>. Read back a new key with <code>SCOPE_IDENTITY()</code> or an <code>OUTPUT</code> clause.","<strong>Unicode is NVARCHAR, time is DATETIME2.</strong> Use <code>N'…'</code> literals, <code>DECIMAL(p,s)</code> for money and <code>SYSDATETIME()</code> (or <code>GETDATE()</code>) for now. The floating-point type is <code>FLOAT</code>, there is no <code>DOUBLE</code>, and <code>DATE</code> holds a date with no time part.","<strong>GO is a client batch separator.</strong> It ends a batch in SSMS and sqlcmd but is not T-SQL, and variables do not survive across it."],"sections":[{"heading":"SELECT basics","rows":[{"what":"Everything from a table","sql":"SELECT * FROM dbo.customers;","note":null,"related_path":null},{"what":"First 10 rows, ordered","sql":"SELECT TOP (10) * FROM dbo.customers ORDER BY last_name;","note":null,"related_path":null},{"what":"Expression with an alias","sql":"SELECT first_name + ' ' + last_name AS full_name FROM dbo.customers;","note":null,"related_path":null},{"what":"Unique values","sql":"SELECT DISTINCT country FROM dbo.customers;","note":null,"related_path":null},{"what":"Conditional value","sql":"SELECT name, CASE WHEN points >= 100 THEN 'gold' ELSE 'standard' END AS tier FROM dbo.members;","note":null,"related_path":null}],"id":"s-select-basics"},{"heading":"Joins","rows":[{"what":"Inner join","sql":"SELECT o.id, c.name FROM dbo.orders o JOIN dbo.customers c ON o.customer_id = c.id;","note":null,"related_path":null},{"what":"Left join keeps unmatched rows","sql":"SELECT c.name, o.id FROM dbo.customers c LEFT JOIN dbo.orders o ON o.customer_id = c.id;","note":null,"related_path":null},{"what":"Both sides, matched or not","sql":"SELECT e.name, m.name FROM dbo.employees e FULL OUTER JOIN dbo.managers m ON m.employee_id = e.id;","note":null,"related_path":null},{"what":"Top N per group with CROSS APPLY","sql":"SELECT c.name, t.placed_at FROM dbo.customers c CROSS APPLY (SELECT TOP (3) o.placed_at FROM dbo.orders o WHERE o.customer_id = c.id ORDER BY o.placed_at DESC) t;","note":null,"related_path":null}],"id":"s-joins"},{"heading":"Filtering","rows":[{"what":"Combined conditions","sql":"SELECT * FROM dbo.orders WHERE country = 'DE' AND placed_at >= '2026-01-01';","note":null,"related_path":null},{"what":"Any of a list","sql":"SELECT * FROM dbo.orders WHERE status IN ('new', 'paid');","note":null,"related_path":null},{"what":"Range","sql":"SELECT * FROM dbo.orders WHERE total BETWEEN 100 AND 500;","note":null,"related_path":null},{"what":"Pattern match","sql":"SELECT * FROM dbo.customers WHERE name LIKE 'A%' AND name NOT LIKE '%test%';","note":null,"related_path":null},{"what":"Exists elsewhere","sql":"SELECT * FROM dbo.customers c WHERE EXISTS (SELECT 1 FROM dbo.orders o WHERE o.customer_id = c.id);","note":null,"related_path":null}],"id":"s-filtering"},{"heading":"Aggregation","rows":[{"what":"Count per group","sql":"SELECT country, COUNT(*) AS customers FROM dbo.customers GROUP BY country;","note":null,"related_path":null},{"what":"Groups after filtering with HAVING","sql":"SELECT customer_id, SUM(total) AS spent FROM dbo.orders GROUP BY customer_id HAVING SUM(total) > 1000;","note":null,"related_path":null},{"what":"Rank within a partition","sql":"SELECT name, department, RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rnk FROM dbo.employees;","note":null,"related_path":null},{"what":"Count distinct values","sql":"SELECT COUNT(DISTINCT country) FROM dbo.customers;","note":null,"related_path":null}],"id":"s-aggregation"},{"heading":"Insert, update, delete","rows":[{"what":"Single and multi-row insert","sql":"INSERT INTO dbo.customers (first_name, last_name) VALUES (N'Ada', N'Lovelace'), (N'Grace', N'Hopper');","note":null,"related_path":null},{"what":"Update through a join","sql":"UPDATE c SET c.tier = 'gold' FROM dbo.customers c JOIN dbo.totals t ON t.customer_id = c.id WHERE t.spent >= 1000;","note":null,"related_path":null},{"what":"Delete in batches","sql":"DELETE TOP (100) FROM dbo.audit_events WHERE archived = 1;","note":null,"related_path":null},{"what":"Upsert with MERGE","sql":"MERGE INTO dbo.targets t USING dbo.sources s ON t.id = s.id WHEN MATCHED THEN UPDATE SET t.name = s.name WHEN NOT MATCHED THEN INSERT (id, name) VALUES (s.id, s.name);","note":null,"related_path":null},{"what":"Read back a new key","sql":"INSERT INTO dbo.customers (first_name) OUTPUT INSERTED.id VALUES (N'Ada');","note":null,"related_path":null}],"id":"s-insert-update-delete"},{"heading":"Create, alter, drop","rows":[{"what":"Create a table","sql":"CREATE TABLE dbo.orders (id BIGINT IDENTITY(1,1) PRIMARY KEY, customer_id BIGINT NOT NULL REFERENCES dbo.customers (id), total DECIMAL(10,2) NOT NULL DEFAULT 0, placed_at DATETIME2 NOT NULL DEFAULT SYSDATETIME());","note":null,"related_path":"/sql-ddl/create-table"},{"what":"Create only if missing","sql":"IF OBJECT_ID(N'dbo.orders', N'U') IS NULL CREATE TABLE dbo.orders (id BIGINT IDENTITY(1,1) PRIMARY KEY, name NVARCHAR(100) NOT NULL);","note":"T-SQL has no IF NOT EXISTS clause: OBJECT_ID checks the catalog first, or DROP TABLE IF EXISTS (2016+) clears the name before the create.","related_path":"/sql-ddl/create-table"},{"what":"Add a column","sql":"ALTER TABLE dbo.customers ADD tier NVARCHAR(20) NOT NULL DEFAULT N'standard';","note":"SQL Server (2012+) makes a NOT NULL add with a constant default a metadata-only change, though it still holds a brief schema-modification lock.","related_path":"/sql-ddl/alter-table-add-column"},{"what":"Change a column type","sql":"ALTER TABLE dbo.customers ALTER COLUMN tier NVARCHAR(40) NOT NULL;","note":"SQL Server refuses while an index, PRIMARY KEY, FOREIGN KEY or CHECK constraint uses the column: drop the constraint, alter, then rebuild it.","related_path":"/sql-ddl/alter-table-alter-column"},{"what":"Drop a column","sql":"ALTER TABLE dbo.customers DROP COLUMN obsolete_a, obsolete_b;","note":"SQL Server refuses while any index, PRIMARY KEY, FOREIGN KEY, CHECK or DEFAULT constraint uses the column, so drop those dependencies first.","related_path":"/sql-ddl/alter-table-drop-column"},{"what":"Rename a table","sql":"EXEC sp_rename 'dbo.orders', 'orders_2025';","note":"sp_rename changes the name only: views and procedures that spell the old name keep running against it until you rewrite them, so search sys.sql_modules afterwards.","related_path":"/sql-ddl/rename-table"},{"what":"Rename a column","sql":"EXEC sp_rename 'dbo.customers.name', 'full_name', 'COLUMN';","note":"T-SQL has no single-statement rename, and sp_rename updates no dependent definitions, hence the caution it prints.","related_path":null},{"what":"Truncate a table","sql":"TRUNCATE TABLE dbo.temp_results;","note":"The statement logs minimally and resets the IDENTITY seed, but fails while any foreign key references the table.","related_path":"/sql-ddl/truncate-table"},{"what":"Copy a table's structure","sql":"SELECT * INTO dbo.orders_backup FROM dbo.orders WHERE 1 = 0;","note":"SELECT INTO carries column types, nullability and IDENTITY but no indexes, PRIMARY KEY or defaults.","related_path":"/sql-ddl/create-table-as"},{"what":"Temp table","sql":"CREATE TABLE #stage (id INT NOT NULL, customer_id BIGINT);","note":"The # prefix makes the table session-local in tempdb, ## makes it global, and the table vanishes when the session ends.","related_path":"/sql-ddl/temp-tables"},{"what":"Drop if it exists (2016+)","sql":"DROP TABLE IF EXISTS dbo.temp_results;","note":null,"related_path":"/sql-ddl/drop-table"}],"id":"s-create-alter-drop"},{"heading":"Indexes","rows":[{"what":"Index a join key","sql":"CREATE INDEX IX_orders_customer_id ON dbo.orders (customer_id);","note":null,"related_path":"/sql-ddl/create-index"},{"what":"Composite index","sql":"CREATE INDEX IX_orders_placed ON dbo.orders (placed_at DESC, customer_id);","note":null,"related_path":null},{"what":"Unique index","sql":"CREATE UNIQUE INDEX UX_customers_email ON dbo.customers (email);","note":null,"related_path":null},{"what":"Covering index with INCLUDE","sql":"CREATE INDEX IX_orders_customer_id ON dbo.orders (customer_id) INCLUDE (total);","note":"INCLUDE columns ride in the index but not in its key, so a matching query reads no table rows at all.","related_path":"/sql-ddl/create-index"},{"what":"Filtered index","sql":"CREATE INDEX IX_orders_open ON dbo.orders (customer_id) WHERE status = 'open';","note":"SQL Server calls the partial index filtered: the WHERE predicate keeps the index to the rows you query.","related_path":null},{"what":"Drop an index","sql":"DROP INDEX IF EXISTS IX_orders_customer_id ON dbo.orders;","note":"T-SQL drops an index per table, so the ON dbo.orders clause is required, and IF EXISTS needs SQL Server 2016+.","related_path":"/sql-ddl/drop-index"}],"id":"s-indexes"},{"heading":"Views","rows":[{"what":"Create a view","sql":"CREATE VIEW dbo.open_orders AS\nSELECT id, customer_id, placed_at, total\nFROM dbo.orders\nWHERE status = 'open';","note":null,"related_path":"/sql-ddl/create-view"},{"what":"Redefine without losing grants","sql":"CREATE OR ALTER VIEW dbo.open_orders AS\nSELECT id, customer_id, total\nFROM dbo.orders WHERE status = 'open';","note":"T-SQL has no OR REPLACE: CREATE OR ALTER VIEW (2016 SP1+) swaps the definition in place and keeps permissions, while a plain CREATE fails once the view exists.","related_path":"/sql-ddl/create-view"},{"what":"Change the query","sql":"ALTER VIEW dbo.open_orders AS\nSELECT id, customer_id, placed_at, total\nFROM dbo.orders WHERE status IN ('open', 'processing');","note":"ALTER VIEW rewrites the definition and the view keeps its grants.","related_path":"/sql-ddl/alter-view"},{"what":"Drop a view","sql":"DROP VIEW IF EXISTS dbo.open_orders;","note":"IF EXISTS needs SQL Server 2016+.","related_path":"/sql-ddl/drop-view"}],"id":"s-views"},{"heading":"String functions","rows":[{"what":"Length and substring","sql":"SELECT LEN(name), SUBSTRING(name, 1, 3) FROM dbo.customers;","note":null,"related_path":null},{"what":"Find and replace","sql":"SELECT CHARINDEX('@', email), REPLACE(code, '-', '') FROM dbo.users;","note":null,"related_path":null},{"what":"Concatenate","sql":"SELECT CONCAT(first_name, ' ', last_name) FROM dbo.customers;","note":null,"related_path":null},{"what":"Trim and change case","sql":"SELECT TRIM(name), UPPER(code), LOWER(email) FROM dbo.customers;","note":null,"related_path":null}],"id":"s-string-functions"},{"heading":"Date functions","rows":[{"what":"Right now","sql":"SELECT SYSDATETIME(), GETDATE();","note":null,"related_path":null},{"what":"Add an interval","sql":"SELECT DATEADD(day, 7, placed_at) FROM dbo.orders;","note":null,"related_path":null},{"what":"Difference between dates","sql":"SELECT DATEDIFF(day, placed_at, SYSDATETIME()) FROM dbo.orders;","note":null,"related_path":null},{"what":"Extract a part","sql":"SELECT DATEPART(year, placed_at), DATEPART(quarter, placed_at) FROM dbo.orders;","note":null,"related_path":null},{"what":"Truncate to a date or the first of the month","sql":"SELECT CAST(placed_at AS date), DATEFROMPARTS(YEAR(placed_at), MONTH(placed_at), 1) FROM dbo.orders;","note":null,"related_path":null},{"what":"Truncate with DATETRUNC (2022+)","sql":"SELECT DATETRUNC(month, placed_at) FROM dbo.orders;","note":null,"related_path":null}],"id":"s-date-functions"},{"heading":"NULL handling","rows":[{"what":"Substitute a default","sql":"SELECT ISNULL(nickname, first_name) FROM dbo.customers;","note":null,"related_path":null},{"what":"First non-NULL of many","sql":"SELECT COALESCE(nickname, first_name, 'unknown') FROM dbo.customers;","note":null,"related_path":null},{"what":"Guard a division by zero","sql":"SELECT total / NULLIF(quantity, 0) FROM dbo.orders;","note":null,"related_path":null},{"what":"Test for NULL","sql":"SELECT * FROM dbo.customers WHERE deleted_at IS NULL;","note":null,"related_path":null}],"id":"s-null-handling"},{"heading":"Paging","rows":[{"what":"Page 3, 10 rows per page","sql":"SELECT * FROM dbo.orders ORDER BY placed_at DESC OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;","note":null,"related_path":null},{"what":"Keyset paging: seek past the last row seen","sql":"SELECT TOP (10) * FROM dbo.orders WHERE placed_at < '2026-01-01' OR (placed_at = '2026-01-01' AND id < 123) ORDER BY placed_at DESC, id DESC;","note":null,"related_path":null}],"id":"s-paging"}],"faqs":[{"question":"How do I limit the number of rows in SQL Server?","answer":"Use SELECT TOP (10) … for a simple cap, or OFFSET … FETCH NEXT … ROWS ONLY after an ORDER BY when you need paging. LIMIT is not T-SQL and is a syntax error."},{"question":"How do I get the ID of the row I just inserted?","answer":"Read SCOPE_IDENTITY() in the same batch, or add an OUTPUT INSERTED.id clause to the INSERT, which also works for multi-row inserts. Avoid @@IDENTITY: it returns the last identity generated in the session in any scope, so a trigger that inserts into another table changes it."},{"question":"What is the difference between GETDATE() and SYSDATETIME()?","answer":"Precision. GETDATE() returns DATETIME, which rounds to .000, .003 or .007 seconds; SYSDATETIME() returns DATETIME2(7), with 100 ns precision. Newer code should default to SYSDATETIME() and DATETIME2."},{"question":"How do I copy a table quickly?","answer":"SELECT INTO creates the table on the fly: SELECT * INTO dbo.orders_backup FROM dbo.orders;. It copies the data, column types, nullability and the IDENTITY property, but not indexes, primary keys, defaults or other constraints."}]},"source_url":"https://sqlly.app/sql-cheat-sheets/sql-server","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-cheat-sheets/sqlite","corpus":"sql-cheat-sheets","engine":"sqlite","language":"en","title":"SQLite cheat sheet","description":"SQLite cheat sheet: LIMIT, joins, INTEGER PRIMARY KEY, INSERT OR REPLACE, ON CONFLICT upserts, date functions on text columns and the type rules that surprise people.","body":{"slug":"sqlite","name":"SQLite","h1":"SQLite cheat sheet","lede":"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.","quirks_html":["<strong>Types are a suggestion.</strong> Columns have affinity, not enforcement: any column can hold TEXT, INTEGER, REAL, BLOB or NULL. <code>INTEGER PRIMARY KEY</code> is the rowid alias and gives you a free auto-incrementing key. Add <code>STRICT</code> after the closing parenthesis (3.37+) to make types enforced.","<strong>Dates are TEXT, REAL or INTEGER.</strong> There is no date storage class (a column declared DATETIME just gets NUMERIC affinity); store ISO-8601 text and use <code>date()</code>, <code>datetime()</code> and <code>strftime()</code> to compute on it.","<strong>LIKE is case-insensitive for ASCII.</strong> <code>GLOB</code> is the case-sensitive, wildcard-with-<code>*</code> cousin.","<strong>Upserts look like Postgres.</strong> <code>INSERT … ON CONFLICT (sku) DO UPDATE SET …</code>, or the older <code>INSERT OR REPLACE</code>, which deletes and re-inserts the row.","<strong>JOIN support grew late.</strong> FULL OUTER and RIGHT JOIN need SQLite 3.39 or newer; older files are INNER/LEFT/CROSS only."],"sections":[{"heading":"SELECT basics","rows":[{"what":"Everything from a table","sql":"SELECT * FROM customers;","note":null,"related_path":null},{"what":"First 10 rows, ordered","sql":"SELECT * FROM customers ORDER BY last_name LIMIT 10;","note":null,"related_path":null},{"what":"Expression with an alias","sql":"SELECT first_name || ' ' || last_name AS full_name FROM customers;","note":null,"related_path":null},{"what":"Unique values","sql":"SELECT DISTINCT country FROM customers;","note":null,"related_path":null},{"what":"Conditional value","sql":"SELECT name, CASE WHEN points >= 100 THEN 'gold' ELSE 'standard' END AS tier FROM members;","note":null,"related_path":null}],"id":"s-select-basics"},{"heading":"Joins","rows":[{"what":"Inner join","sql":"SELECT o.id, c.name FROM orders o JOIN customers c ON o.customer_id = c.id;","note":null,"related_path":null},{"what":"Left join keeps unmatched rows","sql":"SELECT c.name, o.id FROM customers c LEFT JOIN orders o ON o.customer_id = c.id;","note":null,"related_path":null},{"what":"Both sides, matched or not (3.39+)","sql":"SELECT e.name, m.name FROM employees e FULL OUTER JOIN managers m ON m.employee_id = e.id;","note":null,"related_path":null},{"what":"Cross join builds combinations","sql":"SELECT s.name, m.name FROM sizes s CROSS JOIN materials m;","note":null,"related_path":null}],"id":"s-joins"},{"heading":"Filtering","rows":[{"what":"Combined conditions","sql":"SELECT * FROM orders WHERE country = 'DE' AND placed_at >= '2026-01-01';","note":null,"related_path":null},{"what":"Range and lists","sql":"SELECT * FROM orders WHERE total BETWEEN 100 AND 500 AND status IN ('new', 'paid');","note":null,"related_path":null},{"what":"Case-sensitive pattern with GLOB","sql":"SELECT * FROM files WHERE name GLOB '*.log';","note":null,"related_path":null},{"what":"Exists elsewhere","sql":"SELECT * FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);","note":null,"related_path":null}],"id":"s-filtering"},{"heading":"Aggregation","rows":[{"what":"Count per group","sql":"SELECT country, COUNT(*) AS customers FROM customers GROUP BY country;","note":null,"related_path":null},{"what":"Groups after filtering with HAVING","sql":"SELECT customer_id, SUM(total) AS spent FROM orders GROUP BY customer_id HAVING SUM(total) > 1000;","note":null,"related_path":null},{"what":"Aggregate text with group_concat (ORDER BY: 3.44+)","sql":"SELECT country, group_concat(name, ', ' ORDER BY name) FROM customers GROUP BY country;","note":null,"related_path":null},{"what":"Rank within a partition","sql":"SELECT name, department, RANK() OVER (PARTITION BY department ORDER BY salary DESC) FROM employees;","note":null,"related_path":null}],"id":"s-aggregation"},{"heading":"Insert, update, delete","rows":[{"what":"Single and multi-row insert","sql":"INSERT INTO customers (first_name, last_name) VALUES ('Ada', 'Lovelace'), ('Grace', 'Hopper');","note":null,"related_path":null},{"what":"Insert and read back the key (3.35+)","sql":"INSERT INTO customers (first_name) VALUES ('Ada') RETURNING id;","note":null,"related_path":null},{"what":"Upsert with ON CONFLICT","sql":"INSERT INTO stock (sku, count) VALUES ('A1', 5) ON CONFLICT (sku) DO UPDATE SET count = count + excluded.count;","note":null,"related_path":null},{"what":"Insert or replace wholesale","sql":"INSERT OR REPLACE INTO settings (key, value) VALUES ('theme', 'dark');","note":null,"related_path":null},{"what":"Update from another table (3.33+)","sql":"UPDATE products SET price = p.price FROM prices p WHERE p.sku = products.sku;","note":null,"related_path":null}],"id":"s-insert-update-delete"},{"heading":"Create, alter, drop","rows":[{"what":"Create a table","sql":"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')));","note":null,"related_path":"/sql-ddl/create-table"},{"what":"Add a column","sql":"ALTER TABLE customers ADD COLUMN tier TEXT NOT NULL DEFAULT 'standard';","note":"The new column cannot carry UNIQUE or PRIMARY KEY, its DEFAULT must be constant, and SQLite rewrites the schema without touching existing rows.","related_path":"/sql-ddl/alter-table-add-column"},{"what":"Change a column type (rebuild)","sql":"-- no ALTER COLUMN form: rebuild the table\nALTER TABLE orders RENAME TO orders_old;\nCREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL, total NUMERIC(12,2));\nINSERT INTO orders SELECT id, customer_id, total FROM orders_old;\nDROP TABLE orders_old;","note":"The rebuild must recreate the table's indexes, triggers and views by hand, with PRAGMA foreign_keys = OFF for the duration.","related_path":"/sql-ddl/alter-table-alter-column"},{"what":"Rename a column (3.25+)","sql":"ALTER TABLE customers RENAME COLUMN name TO full_name;","note":"Older SQLite builds reject the syntax, and views and triggers on the column follow the rename automatically.","related_path":null},{"what":"Drop a column (3.35+)","sql":"ALTER TABLE customers DROP COLUMN tier;","note":"SQLite 3.35+ added it, and the command refuses while any index, trigger, view, CHECK, FOREIGN KEY or generated column uses the column.","related_path":"/sql-ddl/alter-table-drop-column"},{"what":"Rename a table","sql":"ALTER TABLE customers RENAME TO customers_old;","note":"SQLite 3.25+ rewrites references in views and triggers to follow the rename; older builds left them pointing at the old name.","related_path":"/sql-ddl/rename-table"},{"what":"Truncate (closest form)","sql":"DELETE FROM orders;","note":"SQLite has no TRUNCATE statement; reset an AUTOINCREMENT counter afterwards with DELETE FROM sqlite_sequence WHERE name = 'orders'.","related_path":"/sql-ddl/truncate-table"},{"what":"Temporary table","sql":"CREATE TEMP TABLE stage (id INTEGER PRIMARY KEY, email TEXT);","note":"The table lands in a separate temp database private to this connection and disappears when the connection closes.","related_path":"/sql-ddl/temp-tables"},{"what":"Create a table from a query","sql":"CREATE TABLE big_spenders AS SELECT customer_id, SUM(total) AS spent FROM orders GROUP BY customer_id HAVING SUM(total) > 1000;","note":"Column types come from the query expressions, and every constraint, default and the PRIMARY KEY disappears.","related_path":"/sql-ddl/create-table-as"},{"what":"Drop if it exists","sql":"DROP TABLE IF EXISTS temp_results;","note":null,"related_path":"/sql-ddl/drop-table"}],"id":"s-create-alter-drop"},{"heading":"Indexes","rows":[{"what":"Index a join key","sql":"CREATE INDEX idx_orders_customer_id ON orders (customer_id);","note":null,"related_path":"/sql-ddl/create-index"},{"what":"Index if it does not exist yet","sql":"CREATE INDEX IF NOT EXISTS idx_orders_placed ON orders (placed_at);","note":null,"related_path":null},{"what":"Unique index","sql":"CREATE UNIQUE INDEX ux_customers_email ON customers (email);","note":null,"related_path":null},{"what":"Expression index","sql":"CREATE INDEX idx_customers_email ON customers (lower(email));","note":null,"related_path":null},{"what":"Partial index","sql":"CREATE INDEX idx_orders_open ON orders (customer_id) WHERE status = 'open';","note":null,"related_path":null},{"what":"Drop an index","sql":"DROP INDEX IF EXISTS idx_orders_customer_id;","note":"Indexes share one namespace, so no ON table clause appears, and IF EXISTS works here even though MySQL lacks it.","related_path":"/sql-ddl/drop-index"}],"id":"s-indexes"},{"heading":"Views","rows":[{"what":"Create a view","sql":"CREATE VIEW open_orders AS\nSELECT id, customer_id, total\nFROM orders WHERE status = 'open';","note":null,"related_path":"/sql-ddl/create-view"},{"what":"Rebuild a view","sql":"BEGIN;\nDROP VIEW open_orders;\nCREATE VIEW open_orders AS SELECT id, customer_id, total FROM orders WHERE status IN ('open', 'processing');\nCOMMIT;","note":"SQLite has no OR REPLACE and no ALTER VIEW: drop and recreate inside one transaction so readers never see the view missing.","related_path":"/sql-ddl/alter-view"},{"what":"Drop a view","sql":"DROP VIEW IF EXISTS open_orders;","note":"One view per statement, IF EXISTS included.","related_path":"/sql-ddl/drop-view"}],"id":"s-views"},{"heading":"String functions","rows":[{"what":"Length and case","sql":"SELECT length(name), lower(email), upper(code) FROM customers;","note":null,"related_path":null},{"what":"Substring and position","sql":"SELECT substr(name, 1, 3), instr(email, '@') FROM customers;","note":null,"related_path":null},{"what":"Concatenate with ||","sql":"SELECT first_name || ' ' || last_name FROM customers;","note":null,"related_path":null},{"what":"Trim and replace","sql":"SELECT trim(name), replace(code, '-', '') FROM customers;","note":null,"related_path":null}],"id":"s-string-functions"},{"heading":"Date functions","rows":[{"what":"Right now","sql":"SELECT datetime('now'), date('now');","note":null,"related_path":null},{"what":"Add and subtract days","sql":"SELECT date('now', '-7 day'), date(placed_at, '+1 month') FROM orders;","note":null,"related_path":null},{"what":"Recent rows","sql":"SELECT * FROM orders WHERE placed_at >= datetime('now', '-30 day');","note":null,"related_path":null},{"what":"Format with strftime","sql":"SELECT strftime('%Y-%m', placed_at) AS month, sum(total) FROM orders GROUP BY 1;","note":null,"related_path":null},{"what":"Difference in days","sql":"SELECT julianday('now') - julianday(placed_at) FROM orders;","note":null,"related_path":null}],"id":"s-date-functions"},{"heading":"NULL handling","rows":[{"what":"Substitute a default","sql":"SELECT ifnull(nickname, first_name) FROM customers;","note":null,"related_path":null},{"what":"First non-NULL of many","sql":"SELECT coalesce(nickname, first_name, 'unknown') FROM customers;","note":null,"related_path":null},{"what":"Guard a division by zero","sql":"SELECT total / NULLIF(quantity, 0) FROM orders;","note":null,"related_path":null},{"what":"Test for NULL (= NULL never matches)","sql":"SELECT * FROM customers WHERE deleted_at IS NULL;","note":null,"related_path":null}],"id":"s-null-handling"},{"heading":"Paging","rows":[{"what":"Page 3, 10 rows per page","sql":"SELECT * FROM orders ORDER BY placed_at DESC LIMIT 10 OFFSET 20;","note":null,"related_path":null},{"what":"Fast keyset paging with a row value","sql":"SELECT * FROM orders WHERE (placed_at, id) < ('2026-01-01', 123) ORDER BY placed_at DESC, id DESC LIMIT 10;","note":null,"related_path":null}],"id":"s-paging"}],"faqs":[{"question":"How do I limit rows in SQLite?","answer":"Append LIMIT 10, and OFFSET 20 to skip rows. There is no TOP and no FETCH FIRST."},{"question":"How do I get the ID of the row I just inserted?","answer":"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."},{"question":"Do I need AUTOINCREMENT?","answer":"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."},{"question":"Is the database really just a file?","answer":"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."}]},"source_url":"https://sqlly.app/sql-cheat-sheets/sqlite","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
