Developer Reference & Code Recipes
Database Cheatsheets.
SQL, JDBC, PHP & Node.js
Essential reference cards, production-ready connection snippets, and security best practices for relational database development across modern runtimes.
SQL Queries & Joins
Java JDBC & HikariCP
PHP PDO & MySQLi
Node.js, pg & Prisma
Create Table with Primary Key & Constraints
DDLStandard table creation with auto-increment, unique index, default values, and foreign keys.
sql • 19 lines (629 B)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
CREATE TABLE users (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
role VARCHAR(50) DEFAULT 'member',
is_active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_users_role (role)
);
CREATE TABLE orders (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT NOT NULL,
total_amount DECIMAL(10, 2) NOT NULL,
status VARCHAR(30) DEFAULT 'pending',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT fk_orders_user FOREIGN KEY (user_id)
REFERENCES users (id) ON DELETE CASCADE
);Tags:CREATE TABLEPRIMARY KEYFOREIGN KEYINDEX
Alter Table (Add, Modify, Drop Columns)
DDLModifying schema structure on existing production tables.
sql • 11 lines (365 B)
1
2
3
4
5
6
7
8
9
10
11
-- Add a new column with default value
ALTER TABLE users ADD COLUMN phone VARCHAR(20) NULL AFTER email;
-- Modify column data type or nullability
ALTER TABLE users MODIFY COLUMN name VARCHAR(150) NOT NULL;
-- Add a composite index
ALTER TABLE orders ADD INDEX idx_orders_user_status (user_id, status);
-- Drop a column safely
ALTER TABLE users DROP COLUMN phone;Tags:ALTER TABLEADD COLUMNDROP COLUMN
DML CRUD Operations (Insert, Select, Update, Delete)
DMLFundamental data manipulation operations with filtering and limits.
sql • 20 lines (588 B)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
-- Insert single & multiple rows
INSERT INTO users (name, email, role) VALUES
('Alice Johnson', 'alice@example.com', 'admin'),
('Bob Smith', 'bob@example.com', 'member');
-- Select with conditions, sorting, and pagination
SELECT id, name, email, role
FROM users
WHERE is_active = TRUE AND role != 'banned'
ORDER BY created_at DESC
LIMIT 20 OFFSET 0;
-- Update rows matching a predicate
UPDATE users
SET role = 'manager', is_active = TRUE
WHERE email = 'bob@example.com';
-- Delete specific records
DELETE FROM orders
WHERE status = 'cancelled' AND created_at < NOW() - INTERVAL 30 DAY;Tags:INSERTSELECTUPDATEDELETE
Upsert Patterns (Insert or Update on Conflict)
DMLDialect-specific upsert syntax across MySQL, PostgreSQL, and SQLite.
sql • 13 lines (440 B)
1
2
3
4
5
6
7
8
9
10
11
12
13
-- MySQL / MariaDB
INSERT INTO user_stats (user_id, login_count, last_login)
VALUES (101, 1, NOW())
ON DUPLICATE KEY UPDATE
login_count = login_count + 1,
last_login = VALUES(last_login);
-- PostgreSQL / SQLite (3.24+)
INSERT INTO user_stats (user_id, login_count, last_login)
VALUES (101, 1, CURRENT_TIMESTAMP)
ON CONFLICT (user_id) DO UPDATE SET
login_count = user_stats.login_count + 1,
last_login = EXCLUDED.last_login;Tags:UPSERTON DUPLICATE KEYON CONFLICT
SQL Joins (Inner, Left, Right, Full, Cross)
JoinsComplete reference for combining multiple tables.
sql • 20 lines (662 B)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
-- 1. INNER JOIN (only records present in both tables)
SELECT u.name, o.id AS order_id, o.total_amount
FROM users u
INNER JOIN orders o ON u.id = o.user_id;
-- 2. LEFT JOIN (all left rows, NULL if no match on right)
SELECT u.name, COUNT(o.id) AS total_orders, COALESCE(SUM(o.total_amount), 0) AS total_spent
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id, u.name;
-- 3. Self Join (e.g., employee and manager hierarchy)
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;
-- 4. Cross Join (cartesian product of all combinations)
SELECT s.size, c.color
FROM sizes s
CROSS JOIN colors c;Tags:INNER JOINLEFT JOINRIGHT JOINFULL JOIN
Aggregations, GROUP BY & HAVING
AggregationStatistical grouping with aggregate filters.
sql • 11 lines (320 B)
1
2
3
4
5
6
7
8
9
10
11
-- Grouping with aggregate filters (HAVING filter runs AFTER group aggregation)
SELECT
role,
COUNT(*) AS user_count,
AVG(TIMESTAMPDIFF(YEAR, birth_date, CURDATE())) AS avg_age,
MAX(created_at) AS latest_signup
FROM users
WHERE is_active = TRUE
GROUP BY role
HAVING COUNT(*) >= 5
ORDER BY user_count DESC;Tags:GROUP BYHAVINGCOUNTSUMAVG
Window Functions (ROW_NUMBER, RANK, DENSE_RANK, LEAD, LAG)
Window FunctionsAnalytical calculations across row partitions without collapsing result sets.
sql • 11 lines (388 B)
1
2
3
4
5
6
7
8
9
10
11
-- Rank top 3 highest spending orders per customer
WITH ranked_orders AS (
SELECT
id,
user_id,
total_amount,
ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY total_amount DESC) as rank_num,
LAG(total_amount, 1) OVER(PARTITION BY user_id ORDER BY created_at) as prev_order_amount
FROM orders
)
SELECT * FROM ranked_orders WHERE rank_num <= 3;Tags:ROW_NUMBERRANKDENSE_RANKOVERPARTITION BY
Database Transactions (ACID, Commit & Rollback)
TransactionsAtomic transaction boundaries with rollback on error.
sql • 14 lines (388 B)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
-- MySQL / MariaDB / PostgreSQL
START TRANSACTION;
UPDATE accounts SET balance = balance - 500 WHERE id = 10;
UPDATE accounts SET balance = balance + 500 WHERE id = 20;
-- Verify state before committing
INSERT INTO transfer_logs (from_account, to_account, amount) VALUES (10, 20, 500);
-- If everything succeeded:
COMMIT;
-- In case of any validation or constraint error:
-- ROLLBACK;Tags:BEGINCOMMITROLLBACKSAVEPOINT
