PostgreSQL Complete Study Notes
Day 1: SQL Basics & SELECT Queries
1. Getting Started with PostgreSQL
Setting Up PostgreSQL Command Line
Environment Setup:
· Add PostgreSQL bin folder path to system environment variables
· Connect to PostgreSQL from command prompt:
psql -U postgres
· Enter your PostgreSQL password when prompted
· Now you can use command prompt exactly like SQL shell
Basic Shell Commands
\! cls -- Clear the SQL shell
\list or \li -- Show list of all databases
\c database_name -- Connect to a specific database
\password postgres -- Change PostgreSQL password
System Queries
-- List all databases using system catalog
SELECT datname FROM pg_database;
Note: pg_database is a system catalog table that stores information about all databases in PostgreSQL
cluster. datname column holds database names.
2. Database Operations
Creating Databases
CREATE DATABASE database_name;
· Success message shows: 'CREATE DATABASE'
Deleting Databases
DROP DATABASE database_name WITH (FORCE);
Important Rules:
· You cannot drop a database if other connections are still open
· You must NOT be inside the database you want to delete
· Connect to another database first, then drop the target database
User Management
-- Create new user
CREATE USER user_name WITH PASSWORD '1234';
-- Create database for user
CREATE DATABASE database_name;
-- Grant permissions
GRANT ALL PRIVILEGES ON DATABASE database_name TO user_name;
3. Understanding CRUD Operations
CRUD stands for:
· Create - Adding new data
· Read - Retrieving data
· Update - Modifying existing data
· Delete - Removing data
4. Creating Tables
Table Structure
CREATE TABLE table_name (
id INT,
name VARCHAR(100),
city VARCHAR(100)
);
What each part means:
· id INT → Column for whole numbers (integers)
· name VARCHAR(100) → Text column, maximum 100 characters
· city VARCHAR(100) → Another text column, maximum 100 characters
Data Types (Most Common)
Numeric Types:
· INT - Whole numbers
· DECIMAL(10,2) - Numbers with decimal places
· FLOAT - Floating point numbers
· DOUBLE - Double precision numbers
String Types:
· VARCHAR(n) - Variable length text, max n characters
Other Types:
· DATE - Date values
· BOOLEAN - True/false values
5. Table Constraints
Primary Key
CREATE TABLE customers (
id INT PRIMARY KEY,
name VARCHAR(100)
);
Rules:
· Must be unique (no duplicates)
· Cannot be NULL (must have value)
· Only one primary key per table
· PostgreSQL automatically creates unique index
Not Null
CREATE TABLE customers (
id INT NOT NULL,
name VARCHAR(100) NOT NULL
);
Rule: Column must always have a value, cannot be empty
Default Values
CREATE TABLE employees (
id INT,
status VARCHAR(20) DEFAULT 'Active',
salary DECIMAL(10,2) DEFAULT 30000.00
);
Rule: If no value provided during INSERT, uses the default value
Auto Increment (SERIAL)
CREATE TABLE employees (
emp_id SERIAL PRIMARY KEY,
name VARCHAR(50)
);
What SERIAL does:
· Creates integer column
· Creates automatic sequence (counter)
· Uses sequence as default value
· Automatically generates unique numbers
Unique Constraint
CREATE TABLE users (
id INT PRIMARY KEY,
email VARCHAR(100) UNIQUE
);
Rule: All values in column must be different (allows multiple NULLs)
6. Complete Table Example
CREATE TABLE employees (
emp_id SERIAL PRIMARY KEY,
fname VARCHAR(50) NOT NULL,
lname VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
dept VARCHAR(50),
salary DECIMAL(10,2) DEFAULT 30000.00,
hire_date DATE NOT NULL DEFAULT CURRENT_DATE
);
7. Inserting Data (CREATE)
Basic Insert Syntax
INSERT INTO table_name (column1, column2, column3)
VALUES
(value1, value2, value3),
(value1, value2, value3);
Important Notes:
· List column names in parentheses
· Each row's values in separate parentheses
· Separate multiple rows with commas
· Add semicolon only after the last row
Sample Data Insert
INSERT INTO employees (fname, lname, email, dept, salary, hire_date)
VALUES
('Arjun', 'Verma', '[Link]@[Link]', 'IT', 55000.00, '2021-06-01'),
('Suman', 'Patel', '[Link]@[Link]', 'Finance', 60000.00, '2018-07-30'),
('Kavita', 'Rao', '[Link]@[Link]', 'HR', 47000.00, '2020-11-10');
8. Reading Data (SELECT Queries)
Basic SELECT Syntax
-- Select all columns
SELECT * FROM table_name;
-- Select specific column
SELECT column_name FROM table_name;
-- Select multiple columns
SELECT column1, column2 FROM table_name;
How SELECT works:
1. SELECT → "Show me these columns"
2. column_name → Which columns to display
3. FROM table_name → Which table to look in
9. Filtering Data (WHERE Clause)
Basic WHERE Syntax
SELECT * FROM employees
WHERE emp_id = 5;
Relational Operators
< -- Less than
> -- Greater than
<= -- Less than or equal to
>= -- Greater than or equal to
= -- Equal to
!= -- Not equal to
Logical Operators
AND Operator:
SELECT * FROM employees
WHERE dept = 'IT' AND salary > 50000;
OR Operator:
SELECT * FROM employees
WHERE dept = 'IT' OR dept = 'HR';
IN Operator:
SELECT * FROM employees
WHERE dept IN ('IT', 'HR', 'Finance');
NOT IN Operator:
SELECT * FROM employees
WHERE dept NOT IN ('IT', 'HR', 'Finance');
BETWEEN Operator:
SELECT * FROM employees
WHERE salary BETWEEN 50000 AND 60000;
Note: BETWEEN includes both boundary values
10. Removing Duplicates (DISTINCT)
-- Shows duplicate departments
SELECT dept FROM employees;
-- Shows unique departments only
SELECT DISTINCT dept FROM employees;
Day 2: Filtering, Operators & Functions
11. Sorting Data (ORDER BY)
Basic Sorting
-- Sort ascending (default)
SELECT * FROM employees
ORDER BY fname;
-- Sort descending
SELECT * FROM employees
ORDER BY fname DESC;
-- Sort by multiple columns
SELECT * FROM employees
ORDER BY fname DESC, lname ASC;
12. Limiting Results (LIMIT)
-- Get first 3 rows
SELECT * FROM employees
LIMIT 3;
-- Combine with ORDER BY
SELECT * FROM employees
ORDER BY salary DESC
LIMIT 3;
13. Pattern Matching (LIKE)
LIKE Syntax
column_name LIKE 'pattern'
Wildcards
· % → Any sequence of characters (0 or more)
· _ → Exactly one character
Pattern Examples
-- Starts with 'A'
SELECT * FROM employees
WHERE fname LIKE 'A%';
-- Ends with 'n'
SELECT * FROM employees
WHERE fname LIKE '%n';
-- Contains 'ra' anywhere
SELECT * FROM employees
WHERE fname LIKE '%ra%';
-- Third letter is 'a'
SELECT * FROM employees
WHERE fname LIKE '__a%';
-- Exactly 2 characters
SELECT * FROM employees
WHERE dept LIKE '__';
Case-Insensitive Search (ILIKE)
-- Case-insensitive pattern matching
SELECT * FROM employees
WHERE fname ILIKE 'a%';
14. Aggregate Functions
COUNT Function
-- Count all rows
SELECT COUNT(*) FROM employees;
-- Count non-NULL values in column
SELECT COUNT(dept) FROM employees;
-- Count unique values
SELECT COUNT(DISTINCT dept) FROM employees;
SUM Function
-- Total of all salaries
SELECT SUM(salary) FROM employees;
AVG Function
-- Average salary
SELECT AVG(salary) FROM employees;
MAX and MIN Functions
-- Highest salary
SELECT MAX(salary) FROM employees;
-- Lowest salary
SELECT MIN(salary) FROM employees;
15. Aliases and Expressions
Column Aliases
-- Give column a temporary name
SELECT fname AS first_name, lname AS last_name
FROM employees;
-- Mathematical expression with alias
SELECT salary * 12 AS annual_salary
FROM employees;
Table Aliases
-- Short name for table
SELECT [Link], [Link]
FROM employees AS e;
Text Expressions
-- Combine text columns
SELECT fname || ' ' || lname AS full_name
FROM employees;
16. Updating Data (UPDATE)
UPDATE table_name
SET column_name = 'new_value'
WHERE condition;
Example:
UPDATE employees
SET salary = 65000
WHERE emp_id = 2;
Important: Always use WHERE clause to avoid updating all rows!
17. Deleting Data (DELETE)
DELETE FROM table_name
WHERE condition;
Example:
DELETE FROM employees
WHERE emp_id = 5;
Warning: Without WHERE clause, all rows will be deleted!
Practice Exercises
Day 1 Practice:
1. Create a products table with id, name, price, category
2. Insert 5 sample products
3. Select all products
4. Select only product names and prices
5. Find products with price > 100
Day 2 Practice:
1. Find products in 'Electronics' OR 'Books' category
2. Count total number of products
3. Find average price of all products
4. Get top 3 most expensive products
5. Find products with names starting with 'A'
6. Calculate total value (price * quantity) for each product
Quick Reference
Essential Commands
· \! cls - Clear screen
· \li - List databases
· \c database_name - Connect to database
· SELECT * FROM table_name; - View all data
· COUNT(*) - Count rows
· DISTINCT - Remove duplicates
· LIMIT n - Show first n rows
· ORDER BY column ASC/DESC - Sort data
Common Patterns
· Filter: WHERE condition
· Sort: ORDER BY column
· Limit: LIMIT number
· Count: COUNT(*)
· Average: AVG(column)
· Pattern: LIKE 'pattern%'