postgresql cheatsheet, postgresql tutorial for beginners, postgresql commands list, postgresql sql examples, postgresql create database, postgresql joins, postgresql functions, postgresql vs mysql, postgresql select query, postgresql administration
postgresql cheatsheet, postgresql tutorial for beginners, postgresql commands list, postgresql sql examples, postgresql create database, postgresql joins, postgresql functions, postgresql vs mysql, postgresql select query, postgresql administration

PostgreSQL Cheatsheet — Quick Reference for SQL Developers

PostgreSQL is a powerful open-source relational database management system (RDBMS) that emphasizes data integrity, extensibility, and standards compliance. It supports advanced SQL features, JSON data, and custom functions, making it a favorite among developers for scalable and secure applications.

This PostgreSQL Cheatsheet provides a concise reference of essential commands, SQL syntax, and administrative operations.


Basic PostgreSQL Commands

CommandDescription
psql -U username -d dbnameConnect to a database
\lList all databases
\c database_nameConnect to a specific database
\dtList all tables
\d table_nameDescribe a table
\qQuit psql shell

Database and Table Management

Create and Drop Database

CREATE DATABASE mydb;
DROP DATABASE mydb;

Create and Drop Table

CREATE TABLE employees (
  id SERIAL PRIMARY KEY,
  name VARCHAR(50),
  age INT,
  department VARCHAR(30)
);

DROP TABLE employees;

Alter Table

ALTER TABLE employees ADD COLUMN salary NUMERIC(10,2);
ALTER TABLE employees RENAME COLUMN name TO full_name;
ALTER TABLE employees DROP COLUMN department;

Insert, Update, Delete, and Select Data

Insert Data

INSERT INTO employees (full_name, age, salary)
VALUES ('Alice Brown', 28, 60000);

Select Data

SELECT * FROM employees;
SELECT full_name, salary FROM employees WHERE age > 25;
SELECT DISTINCT department FROM employees;

Update Data

UPDATE employees SET salary = salary + 5000 WHERE age > 30;

Delete Data

DELETE FROM employees WHERE salary < 40000;

Filtering and Sorting Data

SELECT * FROM employees WHERE department = 'HR' ORDER BY salary DESC;
SELECT * FROM employees WHERE age BETWEEN 25 AND 35;
SELECT * FROM employees WHERE full_name LIKE 'A%';

PostgreSQL Joins Explained

Join TypeDescriptionExample
INNER JOINReturns only matching rowsSELECT * FROM a INNER JOIN b ON a.id = b.a_id;
LEFT JOINAll rows from left table + matching from rightSELECT * FROM a LEFT JOIN b ON a.id = b.a_id;
RIGHT JOINAll rows from right table + matching from leftSELECT * FROM a RIGHT JOIN b ON a.id = b.a_id;
FULL OUTER JOINAll rows when there is a match in either tableSELECT * FROM a FULL JOIN b ON a.id = b.a_id;

Aggregate Functions

FunctionDescriptionExample
COUNT()Count number of rowsSELECT COUNT(*) FROM employees;
SUM()Calculate totalSELECT SUM(salary) FROM employees;
AVG()Average valueSELECT AVG(salary) FROM employees;
MAX()Highest valueSELECT MAX(age) FROM employees;
MIN()Lowest valueSELECT MIN(age) FROM employees;

GROUP BY and HAVING Clauses

SELECT department, COUNT(*) AS total
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;

Constraints and Keys

ConstraintDescription
PRIMARY KEYUniquely identifies each row
FOREIGN KEYReferences another table
UNIQUEEnsures all values are different
NOT NULLField cannot be NULL
CHECKEnsures valid data values
DEFAULTSets default value
postgresql cheatsheet, postgresql tutorial for beginners, postgresql commands list, postgresql sql examples, postgresql create database, postgresql joins, postgresql functions, postgresql vs mysql, postgresql select query, postgresql administration

PostgreSQL Functions and Expressions

SELECT NOW();               -- Current timestamp  
SELECT AGE('2025-10-28');   -- Age calculation  
SELECT UPPER('postgres');   -- Convert to uppercase  
SELECT ROUND(45.678, 1);    -- Round to 1 decimal  

Transactions and Rollback

BEGIN;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
UPDATE accounts SET balance = balance + 500 WHERE id = 2;
COMMIT;

Rollback in case of an error:

ROLLBACK;

User and Privilege Management

CREATE USER john WITH PASSWORD 'securePass';
GRANT ALL PRIVILEGES ON DATABASE mydb TO john;
REVOKE INSERT ON TABLE employees FROM john;
DROP USER john;

Indexing for Performance

CREATE INDEX idx_employee_name ON employees(full_name);
DROP INDEX idx_employee_name;

Backup and Restore PostgreSQL Database

Backup:

pg_dump mydb > mydb_backup.sql

Restore:

psql mydb < mydb_backup.sql

PostgreSQL JSON Functions

PostgreSQL fully supports JSON and JSONB.

CREATE TABLE products (
  id SERIAL PRIMARY KEY,
  details JSONB
);

INSERT INTO products (details)
VALUES ('{"name": "Laptop", "brand": "Dell", "price": 800}');

Query JSON Data:

SELECT details->>'name' AS product_name FROM products;

PostgreSQL Performance Tips

  • Use EXPLAIN ANALYZE to inspect query performance.
  • Avoid unnecessary joins with CTEs (Common Table Expressions).
  • Always index columns used in WHERE or JOIN.
  • Use VACUUM ANALYZE to reclaim space and optimize statistics.

FAQ — PostgreSQL Cheatsheet

Q1: What makes PostgreSQL different from MySQL?
PostgreSQL supports complex queries, JSON data, and ACID compliance, making it ideal for enterprise applications.

Q2: Is PostgreSQL open source?
Yes, PostgreSQL is completely free and open source under the PostgreSQL License.

Q3: Can I use PostgreSQL for web development?
Yes, it’s widely used with frameworks like Django, Laravel, and Node.js.

Q4: What port does PostgreSQL use by default?
PostgreSQL uses port 5432 by default.

Q5: How can I connect PostgreSQL to PHP or Python?
Use pg_connect() in PHP or psycopg2 in Python to establish a database connection.

Related Article
Machine Learning Cheatsheet (Unsupervised & Reinforcement Learning)

Machine Learning (ML) is a crucial part of artificial intelligence, enabling systems to automatically learn from data.This Machine Learning Cheatsheet Read more

HTML Cheat Sheet — Reference Guide to HTML Tags, Attributes, and Examples

HTML cheat sheet, HTML tags reference, HTML attributes list, HTML examples for beginners, semantic HTML guide, HTML forms tutorial, HTML Read more

Python Cheat Sheet — Complete Syntax Reference and Programming Examples

This Python Cheat Sheet is your quick reference guide for writing efficient Python code. Whether you’re preparing for coding interviews, Read more

PHP Cheat Sheet — Complete Syntax Reference and Programming Examples for Beginners

PHP Cheat Sheet — Complete Syntax Reference & Examples This PHP Cheat Sheet serves as a quick, structured reference for Read more

JavaScript Cheat Sheet — Complete ES6 Syntax, Functions, and DOM Methods with Examples

JavaScript Cheat Sheet — Complete Syntax Reference & Examples JavaScript is the core scripting language of the web, enabling interactivity, Read more

CSS Cheat Sheet — Complete CSS3 Selectors, Properties, and Layout Examples

CSS Cheat Sheet — Complete CSS3 Syntax, Selectors & Layout Examples Cascading Style Sheets (CSS) is the language used to Read more

Java Cheat Sheet — Complete Java Syntax, Data Types, Loops, and OOP Concepts for Beginners

Java Cheat Sheet — Complete Java Syntax, Classes, and Examples Java is a powerful, object-oriented programming language widely used for Read more

HTML5 Cheat Sheet — Complete Tag Reference & Examples

HTML5 is the core markup language of the modern web, used to structure content such as text, images, forms, and Read more

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments