Oracle cheat sheet
Everyday Oracle SQL in the dialect Oracle speaks, not the one the other engines share: dual, sequences, FETCH FIRST, LISTAGG and TO_CHAR.
sqlly.app/sql-cheat-sheets/oracle
SELECT basics
- Everything from a table
SELECT * FROM customers;- First 10 rows, ordered
SELECT * FROM customers ORDER BY last_name FETCH FIRST 10 ROWS ONLY;- Evaluate an expression without a table
SELECT SYSDATE, 1 + 1 FROM dual;- Expression with an alias
SELECT first_name || ' ' || last_name AS full_name FROM customers;- Unique values
SELECT DISTINCT country FROM customers;
聯結
- 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
SELECT e.name, m.name FROM employees e FULL OUTER JOIN managers m ON m.employee_id = e.id;- Old-style outer join: (+) marks the optional side
SELECT c.name, o.id FROM customers c, orders o WHERE o.customer_id (+) = c.id;
篩選
- Combined conditions
SELECT * FROM orders WHERE country = 'DE' AND placed_at >= DATE '2026-01-01';- Range and lists
SELECT * FROM orders WHERE total BETWEEN 100 AND 500 AND status IN ('new', 'paid');- Pattern match
SELECT * FROM customers WHERE name LIKE 'A%' AND name NOT LIKE '%test%';- 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 LISTAGG
SELECT country, LISTAGG(name, ', ') WITHIN GROUP (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
- Insert with a sequence key
INSERT INTO orders (id, customer_id, total) VALUES (orders_seq.NEXTVAL, 42, 99.90);- Update with a subquery
UPDATE customers SET tier = 'gold' WHERE id IN (SELECT customer_id FROM totals WHERE spent >= 1000);- Delete a bounded batch
DELETE FROM audit_events WHERE archived = 1 AND ROWNUM <= 100;- Upsert with MERGE
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);
Create, alter, drop
- Create a table
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);- Add a column
ALTER TABLE customers ADD (tier VARCHAR2(20) DEFAULT 'standard' NOT NULL);- Change a column type
ALTER TABLE customers MODIFY (tier VARCHAR2(40));- Drop, skipping the recycle bin
DROP TABLE temp_results PURGE;- Drop if it exists (23ai+)
DROP TABLE IF EXISTS temp_results;
索引
- Index a join key
CREATE INDEX idx_orders_customer_id ON orders (customer_id);- Composite index
CREATE INDEX idx_orders_placed ON orders (placed_at DESC, customer_id);- Unique index
CREATE UNIQUE INDEX ux_customers_email ON customers (email);- Function-based index
CREATE INDEX idx_customers_email ON customers (UPPER(email));
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;- Pad and trim
SELECT LPAD(id, 6, '0'), TRIM(name) FROM customers;- 取代
SELECT REPLACE(code, '-', '') FROM customers;
Date functions
- 現在
SELECT SYSDATE, SYSTIMESTAMP FROM dual;- Add months
SELECT ADD_MONTHS(SYSDATE, -3) FROM dual;- Truncate to a month
SELECT TRUNC(placed_at, 'MM') AS month, SUM(total) FROM orders GROUP BY TRUNC(placed_at, 'MM');- Format a date
SELECT TO_CHAR(placed_at, 'YYYY-MM-DD') FROM orders;- Parse a date safely
SELECT * FROM orders WHERE placed_at >= TO_DATE('2026-01-01', 'YYYY-MM-DD');- Months between two dates
SELECT MONTHS_BETWEEN(SYSDATE, placed_at) FROM orders;
NULL handling
- Substitute a default
SELECT NVL(nickname, first_name) FROM customers;- Two outcomes with NVL2
SELECT NVL2(phone, 'has phone', 'no phone') FROM customers;- First non-NULL of many
SELECT COALESCE(nickname, first_name, 'unknown') FROM customers;- The empty string is NULL
SELECT * FROM tasks WHERE note IS NULL;
Paging
- Page 3, 10 rows per page (12c+)
SELECT * FROM orders ORDER BY placed_at DESC OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;- Top N before 12c with ROWNUM
SELECT * FROM (SELECT * FROM customers ORDER BY last_name) WHERE ROWNUM <= 10;
Oracle quirks worth knowing
- Selects needed a table, so there is dual.
SELECT SYSDATE FROM dual;evaluates an expression without data. Oracle 23ai finally allowsSELECT SYSDATE;with no FROM, but code that must run on 19c still needs dual. - Row counts use FETCH FIRST or ROWNUM.
FETCH FIRST 10 ROWS ONLY(12c and newer) or the olderROWNUMin a subquery. There is no LIMIT. - The empty string is NULL.
''compares as NULL in Oracle, soNVL和IS NULLsee them the same way. - DATE has a time. An Oracle
DATEstores year to second;TIMESTAMPadds fractional seconds. Convert explicitly withTO_CHAR和TO_DATE. - Names fold to uppercase. Unquoted identifiers become uppercase, the mirror image of PostgreSQL folding them to lowercase; quoted
"MixedCase"keeps its case forever.
Other SQL cheat sheets
To run this sheet against a live database, get the SQLly desktop app for Oracle,或瀏覽所有 功能.
Oracle cheat sheet FAQ
How do I limit rows in Oracle?
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.
What is the dual table?
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.
Why does '' behave like NULL?
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.
How do I get the key of a row I just inserted?
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.
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.