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 employeeSET salary = 60000WHERE id = 1;4. Delete β DELETE
Remove records from a table.
DELETE FROM employeeWHERE 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 employeeWHERE salary > 40000;πΉ ORDER BY
Sort results.
SELECT * FROM employeeORDER BY salary DESC;πΉ GROUP BY
Group rows for aggregation.
SELECT department, AVG(salary) AS avg_salaryFROM employeeGROUP BY department;πΉ HAVING
Apply conditions after grouping.
SELECT department, AVG(salary) AS avg_salaryFROM employeeGROUP BY departmentHAVING AVG(salary) > 50000;πΉ LIMIT / OFFSET
Restrict rows returned.
SELECT * FROM employeeLIMIT 5;SELECT * FROM employeeORDER BY idLIMIT 5 OFFSET 5;πΉ LIKE
Search for patterns inside text.
SELECT * FROM employeeWHERE name LIKE 'S%';β Finds names starting with S (e.g., Saurabh, Sneha).
SELECT * FROM employeeWHERE 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
| Operation | Keyword | Example |
|---|---|---|
| Create | INSERT | INSERT INTO employee (...) VALUES (...); |
| Read | SELECT | SELECT * FROM employee; |
| Update | UPDATE | UPDATE employee SET salary=... WHERE id=...; |
| Delete | DELETE | DELETE FROM employee WHERE id=...; |
| Clause | Purpose | Example |
|---|---|---|
WHERE | Filter rows | salary > 40000 |
ORDER BY | Sort results | ORDER BY salary DESC |
GROUP BY | Group rows | GROUP BY department |
HAVING | Condition after grouping | HAVING AVG(salary) > 50000 |
LIMIT | Restrict rows | LIMIT 5 |
LIKE | Pattern search | name LIKE 'S%' |
DISTINCT | Unique values only | SELECT DISTINCT department FROM ... |