PostgreSQL - Cheatsheet
PostgreSQL Modern Cheatsheet
Section titled “PostgreSQL Modern Cheatsheet”This PostgreSQL cheatsheet provides a quick reference to essential commands and modern best practices. PostgreSQL is a powerful, open-source object-relational database system known for its reliability, feature robustness, and performance. This guide will help you use PostgreSQL effectively in modern applications.
.toc_container {
width: 100%;
clear: both;
display: table;
}
.toc_column {
width: 50%;
float: left;
}
@media (max-width: 600px) {
.toc_column {
width: 100%;
float: none;
}
.second_child {
margin-top: -15px;
}
}
1. Connecting to PostgreSQL
Section titled “1. Connecting to PostgreSQL”Use the psql command-line tool. The easiest way to run PostgreSQL for local development is with Docker:
# Start PostgreSQL in Dockerdocker run --name my-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d postgres
# Connect using psqlpsql --host=localhost --username=postgres --dbname=postgresCheck the server version:
SELECT version();2. Data Definition Language (DDL)
Section titled “2. Data Definition Language (DDL)”Create Table
Section titled “Create Table”Use GENERATED ALWAYS AS IDENTITY for auto-incrementing primary keys (SQL standard, available since Postgres 10). Use modern data types like UUID, TIMESTAMPTZ, and JSONB.
CREATE TABLE employees ( id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, employee_uuid UUID DEFAULT gen_random_uuid(), name VARCHAR(100) NOT NULL, email VARCHAR(100) UNIQUE NOT NULL, department VARCHAR(50), salary NUMERIC(10, 2), created_at TIMESTAMPTZ DEFAULT NOW());Alter Table
Section titled “Alter Table”-- Add a columnALTER TABLE employees ADD COLUMN start_date DATE;
-- Rename a columnALTER TABLE employees RENAME COLUMN start_date TO hire_date;
-- Drop a columnALTER TABLE employees DROP COLUMN hire_date;
-- Add a constraintALTER TABLE employees ADD CONSTRAINT salary_check CHECK (salary > 0);Drop Table
Section titled “Drop Table”DROP TABLE IF EXISTS employees;3. Data Manipulation Language (DML)
Section titled “3. Data Manipulation Language (DML)”Insert Data
Section titled “Insert Data”-- Insert a single rowINSERT INTO employees(name, email, department, salary)VALUES('Alice', 'alice@example.com', 'Engineering', 90000);
-- Insert multiple rowsINSERT INTO employees(name, email, department, salary) VALUES('Bob', 'bob@example.com', 'Engineering', 95000),('Charlie', 'charlie@example.com', 'Marketing', 85000);Update Data
Section titled “Update Data”UPDATE employeesSET salary = salary * 1.05, department = 'Senior Engineering'WHERE email = 'bob@example.com';Delete Data
Section titled “Delete Data”DELETE FROM employees WHERE email = 'charlie@example.com';4. Data Query Language (DQL)
Section titled “4. Data Query Language (DQL)”SELECT name, salary FROM employeesWHERE department = 'Engineering'ORDER BY salary DESCLIMIT 10;Aggregate Functions
Section titled “Aggregate Functions”-- Get statistics for the Engineering departmentSELECT COUNT(*) AS num_employees, AVG(salary) AS avg_salary, MIN(salary) AS min_salary, MAX(salary) AS max_salary, SUM(salary) AS total_payrollFROM employeesWHERE department = 'Engineering';Grouping Data
Section titled “Grouping Data”SELECT department, AVG(salary) as avg_dept_salaryFROM employeesGROUP BY departmentHAVING COUNT(*) > 5; -- Filter groups after aggregationSELECT e.name, p.project_nameFROM employees AS eINNER JOIN projects AS p ON e.id = p.employee_id;Pattern Matching
Section titled “Pattern Matching”-- Case-sensitive searchSELECT name FROM employees WHERE name LIKE 'A%';
-- Case-insensitive search (Postgres-specific)SELECT name FROM employees WHERE name ILIKE 'a%';5. Advanced Querying
Section titled “5. Advanced Querying”Common Table Expressions (CTEs)
Section titled “Common Table Expressions (CTEs)”Use CTEs (the WITH clause) to break down complex queries into logical, readable steps.
WITH high_earners AS ( SELECT id, name, department FROM employees WHERE salary > 100000)SELECT * FROM high_earners WHERE department = 'Engineering';Window Functions
Section titled “Window Functions”Perform calculations across a set of table rows that are somehow related to the current row.
-- Rank employees by salary within each departmentSELECT name, department, salary, RANK() OVER (PARTITION BY department ORDER BY salary DESC) as dept_rankFROM employees;The CASE Statement
Section titled “The CASE Statement”SELECT name, salary, CASE WHEN salary > 100000 THEN 'High' WHEN salary > 70000 THEN 'Medium' ELSE 'Standard' END AS salary_gradeFROM employees;6. Transactions and Data Integrity
Section titled “6. Transactions and Data Integrity”Transactions
Section titled “Transactions”Wrap multiple statements in a transaction to ensure they all succeed or fail together (atomicity).
BEGIN;UPDATE accounts SET balance = balance - 100 WHERE id = 1;UPDATE accounts SET balance = balance + 100 WHERE id = 2;COMMIT; -- Or ROLLBACK to undo changesIndexes
Section titled “Indexes”Create indexes to speed up query performance. Foreign keys are often good candidates for indexes.
-- Create an index on a frequently queried columnCREATE INDEX idx_employees_department ON employees(department);
-- Use EXPLAIN to analyze query performanceEXPLAIN ANALYZE SELECT * FROM employees WHERE department = 'Engineering';