Postgre SQL
Postgre SQL
#PostgreSQL#
Prepared by: Rohit S. Patil(Sr. Business Analyst)
Mob: +91 9767548985
Email: [email protected]
Create Database:
Drop Database:
Rohit S. Patil
2
SYNTAX:
CREATE TABLE <TABLE NAME>(
column1 datatype [constraints],
column2 datatype [constraints],
column3 datatype [constraints],
—---------
);
EX: CREATE TABLE students(
student_id SERIAL PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
birth_date DATE,
email varchar(100) UNIQUE,
phone_number VARCHAR(15),
Enrollment_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Rohit S. Patil
3
DELETE a table:
Rohit S. Patil
4
Rohit S. Patil
5
CONSTRAINTS:
Rohit S. Patil
6
INSERT INTO employee (emp_id, name, email, phone, hire_date, designation, salary,
dept)
VALUES (1, 'Rohit Patil', '[email protected]', '9767548985', '2023-07-24', 'Sr.
Business Analyst', 60000, 'Business Analyst');
INSERT 0 1
INSERT INTO employee (name, email, phone, hire_date, designation, salary, dept)
VALUES ('Priya Singh, '[email protected]', '9875485689', '2023-01-24', 'Software
Developer', 70000, 'Software Development');
Error: Key (emp_id)=(1) already exists.duplicate key value violates unique constraint
"employee_pkey"
Rohit S. Patil
7
Open SqlShell[psql] - Connect to the Database and Describe the Table using \d employee;
Copy - nextval(‘employee_emp_id_seq’)
INSERT INTO employee (name, email, phone, hire_date, designation, salary, dept)
VALUES ('Priya Singh, '[email protected]', '9875485689', '2023-01-24', 'Software
Developer', 70000, 'Software Development');
Stored Routine:
Rohit S. Patil
8
Rohit S. Patil
9
END;
$$;
Rohit S. Patil
10
—--Function Logic—--
RETURN VALUE;
END;
$$ LANGUAGE plpgsql;
EX: 1.
CREATE OR REPLACE FUNCTION calculate_bonus(emp_salary NUMERIC,
emp_experience INT)
RETURNS NUMERIC AS $$
BEGIN
Rohit S. Patil
11
END IF;
END;
$$ LANGUAGE plpgsql;
Function Name: calculate_bonus
Input Parameters:
emp_salary NUMERIC → Employee's salary
emp_experience INT → Employee's years of experience
Return Type: NUMERIC (returns the calculated bonus)
Logic Inside the Function:
If the employee has more than 10 years of experience, they receive 20% of their salary as
a bonus.
If the experience is between 5 and 10 years, they receive 10% of their salary as a bonus.
If the experience is less than 5 years, they receive 5% of their salary as a bonus.
Return Statement: Based on the conditions, the function returns the appropriate bonus
amount.
EX: 2.
CREATE OR REPLACE FUNCTION get_grade(score NUMERIC)
RETURNS TEXT AS $$
BEGIN
IF score>=90 THEN
RETURN 'A';
ELSIF score>=80 THEN
RETURN 'B';
ELSIF score>=70 THEN
RETURN 'C';
ELSIF score>=60 THEN
RETURN 'D';
ELSE
RETURN 'F';
Rohit S. Patil
12
END IF;
END;
$$ LANGUAGE plpgsql
CLAUSES:
1. WHERE:
○ SELECT * FROM employee WHERE emp_id = 5;
○ SELECT * FROM employee WHERE dept = ‘HR’
2. Relational Operator: < Less Than, > Greater Than, <= Less Than Equal To, >= Greater
Than Equal To, = Equal To, != Not Equal To
○ SELECT * FROM employee WHERE dept= ‘BA’ OR fname= ‘Rohit’;
—-----Atleast one Condition should be True
○ SELECT * FROM employee WHERE dept = ‘HR’ AND Salary >= 40000;
—---- Both Condition Should be True
3. IN Operator:
○ SELECT * FROM employee WHERE dept IN(‘IT’, ‘HR’, ‘BA’);
4. NOT IN Operator
○ SELECT * FROM employee WHERE dept NOT IN(‘IT’, ‘HR’, ‘BA’);
5. BETWEEN
○ SELECT * FROM employee WHERE salary BETWEEN 40000 AND 60000;
6. DISTINCT
○ SELECT DISTINCT dept FROM employee; — Only Distinct Values
7. ORDER BY: Ascending or Descending Order
○ SELECT * FROM employee ORDER BY emp_id;
○ SELECT * FROM employee ORDER BY emp_id DESC;
8. LIMIT:
○ SELECT * FROM employee LIMIT 3; —-Starting 3 Rows Only
9. LIKE:
○ SELECT * FROM employee WHERE fname LIKE ‘%A’; — a should be in the
end of fname
○ SELECT * FROM employee WHERE fname LIKE ‘A%’; — a should be in the
First of fname
○ SELECT * FROM employee WHERE dept LIKE ‘--’; — Two characters of Dept
Value
Rohit S. Patil
13
GROUP BY Functions: -
CREATING SCHEMA: -
Rohit S. Patil
14
CONCAT:
● SELECT CONCAT(‘Hello’, ‘World’); - HelloWorld
● SELECT CONCAT(fname, lname) AS fullname FROM employee; - Rohitpatil
● SELECT emp_id CONCAT(fname,lname) AS fullname, dept FROM employee; - 1,
Rohitpatil, IT
● SELECT emp_id CONCAT(fname, ‘ ’, lname) AS fullname, dept FROM employee; - 1,
Rohit patil, IT
CONCAT_WS(With Separator):
SUBSTRING FUNCTIONS:
SUBSTR
● SELECT SUBSTR(‘Hello Buddy’, 1, 6); - Hello
● SELECT SUBSTR(‘Hello Buddy!’, 7, 12); - Buddy!
REPLACE REPLACE(str, from_str, to_str);
● SELECT REPLACE(‘Hey Buddy’, ‘Hey’, ‘Hello’); - Hello Buddy
● SELECT REPLACE(dept, 'Software Development', 'Tech') AS updated_dept
FROM company.employee;
REVERSE
● SELECT REVERSE(fname) FROM employee; - tihoR
LENGTH
● SELECT LENGTH(fname) FROM employee;
● SELECT * FROM employee WHERE LENGTH(fname) >5;
UPPER & LOWER:
● SELECT UPPER(fname) FROM employee; - ROHIT
● SELECT LOWER(fname) FROM employee; - rohit
LEFT & RIGHT:
● SELECT LEFT(‘Hello World’, 4); - Hell
● SELECT RIGHT(‘Hello World’, 5); - World
TRIM: Function Inside Function
● SELECT LENGTH(‘ Alright ’); - Length: 14
● SELECT LENGTH(TRIM(‘ Alright ’)); - Length: 7
POSITION
Rohit S. Patil
15
ALTERING TABLES
● ADD
■ Ex: ALTER TABLE Employee
ADD column age INT;
● REMOVE
■ Ex: ALTER TABLE Employee
DROP column age;
● RENAME - Column Name
■ EX: ALTER TABLE Employee
RENAME name to full_name
● SET DEFAULT:
■ ALTER TABLE people
ALTER COLUMN dept
SET DEFAULT 'BusinessAnalyst';
● DROP DEFAULT:
■ ALTER TABLE people
ALTER COLUMN dept DROP DEFAULT;
Rohit S. Patil
16
CHECK CONSTRAINTS:
DROP CONSTRAINTS:
Rohit S. Patil
17
CASE:
Ex. SELECT fname, salary,
CASE
WHEN salary>=5000 THEN ‘HIGH’
WHEN salary BETWEEN 48000 AND 50000 THEN ‘MID’
ELSE ‘LOW’
END AS sal_category FROM employee;
Rohit S. Patil
18
('Bob Johnson');
Output:
Rohit S. Patil
19
Output:
Rohit S. Patil
20
Rohit S. Patil
21
SELECT
s.id AS student_id,
s.name AS student_name,
c.id AS course_id,
c.title AS course_title
FROM student s
JOIN student_course sc ON s.id = sc.student_id
JOIN course c ON sc.course_id = c.id
ORDER BY s.id;
Output:
Rohit S. Patil
22
JOINS: INNER JOIN, CROSS JOIN, FULL JOIN, LEFT JOIN, RIGHT JOIN
Rohit S. Patil
23
Rohit S. Patil
24
4️⃣ FULL JOIN (All students and enrollments, NULL where no match)
Rohit S. Patil
25
VIEWS:
Rohit S. Patil
26
s.id AS student_id,
s.name AS student_name,
c.id AS course_id,
c.title AS course_title
FROM student s
JOIN student_course sc ON s.id = sc.student_id
JOIN course c ON sc.course_id = c.id
ORDER BY s.id;
Having clause:
CREATE TABLE orders (
order_id SERIAL PRIMARY KEY,
customer_id INT NOT NULL,
total_amount DECIMAL(10,2) NOT NULL
);
Output:
Rohit S. Patil
27
CREATE INDEX creates an index on a table to improve query performance.
Output:
Rohit S. Patil
28
SELECT
COALESCE(region, 'Total') AS region,
COALESCE(category, 'Subtotal') AS category,
SUM(revenue) AS total_revenue
FROM sales
GROUP BY ROLLUP (region, category)
ORDER BY region NULLS LAST, category NULLS LAST;
Rohit S. Patil
29
Explanation:
1. ROLLUP (region, category):
○ Groups by region and category, computing subtotals for each region and a
grand total.
OUTPUT:
Rohit S. Patil
30
Window Function:
CREATE TABLE students (
id SERIAL PRIMARY KEY,
name VARCHAR(50),
class VARCHAR(10),
subject VARCHAR(50),
marks INT
);
Output:
Rohit S. Patil
31
PostgreSQL's OVER() clause defines how a window function processes rows. It controls:
● Partitioning (PARTITION BY) – Divides rows into groups before applying the
function.
● Ordering (ORDER BY) – Defines the sequence in which the function processes rows.
● Framing (ROWS BETWEEN ... AND ...) – Specifies the range of rows for calculations
(optional)
Output:
Rohit S. Patil
32
Output:
Rohit S. Patil
33
Use a CTE:
WITH avg_salary AS (
SELECT department, AVG(salary) AS dept_avg_salary
FROM employees
GROUP BY department
)
SELECT e.name, e.department, e.salary, a.dept_avg_salary
FROM employees e
JOIN avg_salary a ON e.department = a.department
WHERE e.salary > a.dept_avg_salary;
OUTPUT:
✅ Explanation
1️⃣ CTE (avg_salary) calculates the average salary per department.
2️⃣ Main query joins employees with avg_salary to compare each employee’s salary with
the department average.
3️⃣ . Filters out employees earning more than the department average.
Rohit S. Patil
34
Rohit S. Patil