Skip to content

PostgreSQL Basics (CRUD + Clauses)

This guide explains the fundamentals of PostgreSQL, focusing on CRUD operations and the most important SQL clauses.
It’s written in simple language with examples you can try right away.


🟦 CRUD Operations

CRUD stands for Create, Read, Update, Delete β€” the four main operations you perform on data.


1. Create β†’ INSERT

Add new records into a table.

INSERT INTO employee (id, name, salary, department)
VALUES (1, 'Saurabh', 50000, 'IT');

2. Read β†’ SELECT

Retrieve records from a table.

SELECT * FROM employee;

βœ… Shows all rows and columns.

SELECT name, salary FROM employee;

βœ… Shows only selected columns.


3. Update β†’ UPDATE

Modify existing records.

UPDATE employee
SET salary = 60000
WHERE id = 1;

4. Delete β†’ DELETE

Remove records from a table.

DELETE FROM employee
WHERE id = 1;

⚠️ To remove all rows but keep the table:

DELETE FROM employee;

⚠️ To remove the table itself:

DROP TABLE employee;

🟩 Important SQL Clauses in PostgreSQL

Clauses help filter, group, or sort data when querying.


πŸ”Ή WHERE

Filter rows based on a condition.

SELECT * FROM employee
WHERE salary > 40000;

πŸ”Ή ORDER BY

Sort results.

SELECT * FROM employee
ORDER BY salary DESC;

πŸ”Ή GROUP BY

Group rows for aggregation.

SELECT department, AVG(salary) AS avg_salary
FROM employee
GROUP BY department;

πŸ”Ή HAVING

Apply conditions after grouping.

SELECT department, AVG(salary) AS avg_salary
FROM employee
GROUP BY department
HAVING AVG(salary) > 50000;

πŸ”Ή LIMIT / OFFSET

Restrict rows returned.

SELECT * FROM employee
LIMIT 5;
SELECT * FROM employee
ORDER BY id
LIMIT 5 OFFSET 5;

πŸ”Ή LIKE

Search for patterns inside text.

SELECT * FROM employee
WHERE name LIKE 'S%';

βœ… Finds names starting with S (e.g., Saurabh, Sneha).

SELECT * FROM employee
WHERE name LIKE '%a%';

βœ… Finds names containing the letter a.


πŸ”Ή DISTINCT

Return unique values only.

SELECT DISTINCT department FROM employee;

βœ… Lists each department once, even if many employees belong to it.


βœ… Quick Summary

OperationKeywordExample
CreateINSERTINSERT INTO employee (...) VALUES (...);
ReadSELECTSELECT * FROM employee;
UpdateUPDATEUPDATE employee SET salary=... WHERE id=...;
DeleteDELETEDELETE FROM employee WHERE id=...;
ClausePurposeExample
WHEREFilter rowssalary > 40000
ORDER BYSort resultsORDER BY salary DESC
GROUP BYGroup rowsGROUP BY department
HAVINGCondition after groupingHAVING AVG(salary) > 50000
LIMITRestrict rowsLIMIT 5
LIKEPattern searchname LIKE 'S%'
DISTINCTUnique values onlySELECT DISTINCT department FROM ...