Postgre SQL Advance Notes
Postgre SQL Advance Notes
Installation
Windows: Download the installer from the official PostgreSQL website and follow the setup
wizard. During installation, note the password and port (default: 5432) [1] .
Linux: Use your package manager, e.g., on Ubuntu:
sudo apt update
sudo apt install postgresql postgresql-contrib
pgAdmin: A graphical tool installed with PostgreSQL for database management [2] [1] .
Create Table:
CREATE TABLE employees (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
age INT,
salary NUMERIC(10,2)
);
Insert Data in the Table
Constraints:
PRIMARY KEY, UNIQUE, NOT NULL, CHECK, FOREIGN KEY
Example:
Update Data
Query Toolbar
In pgAdmin, use the "Query Tool" to write and execute SQL queries.
Directly in pgAdmin:
Right-click the table → "Import/Export Data" → select CSV file and options.
Arithmetic +, -, *, /, %
Logical Operators
AND, OR, NOT
LIKE:
SELECT * FROM employees WHERE name LIKE 'A%';
IN:
SELECT * FROM employees WHERE department IN ('HR', 'IT');
Other Operators
IS NULL, IS NOT NULL
EXISTS
ANY, ALL
Set Operators
UNION, UNION ALL, INTERSECT, EXCEPT
Functions in SQL
Aggregate: COUNT(), SUM(), AVG(), MIN(), MAX()
String: UPPER(), LOWER(), LENGTH(), SUBSTRING()
Date/Time: NOW(), CURRENT_DATE, AGE()
Conditional: CASE, COALESCE()
Window: ROW_NUMBER(), RANK(), DENSE_RANK(), OVER()
String Functions
UPPER('abc') → 'ABC'
LOWER('ABC') → 'abc'
LENGTH('hello') → 5
SUBSTRING('abcdef', 2, 3) → 'bcd'
Conditional Functions
CASE:
SELECT name,
CASE
WHEN salary > 60000 THEN 'High'
ELSE 'Low'
END AS salary_level
FROM employees;
COALESCE:
SELECT COALESCE(middle_name, 'N/A') FROM employees;
Window Functions
Used for calculations across a set of table rows related to the current row.
Examples: ROW_NUMBER(), RANK(), SUM() OVER (PARTITION BY department)
Joins
Join Type Description
LEFT JOIN All rows from left table, matched rows from right table
RIGHT JOIN All rows from right table, matched rows from left table
Example:
SELECT a.name, b.department_name
FROM employees a
INNER JOIN departments b ON a.department_id = b.id;
WITH dept_count AS (
SELECT department, COUNT(*) AS num
FROM employees
GROUP BY department
)
SELECT * FROM dept_count WHERE num > 5;
Subquery
Query inside another query.
SELECT name FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);
Tip: Practice each command in pgAdmin or psql for hands-on learning [5] [2] [1] .
⁂
PostgreSQL Functions: Syntax, Explanation, and Examples
Below you'll find explanations, syntax, and practical examples for each major PostgreSQL
function category discussed previously.
1. Aggregate Functions
Aggregate functions perform calculations on sets of rows and return a single value.
Group By Example:
2. String Functions
String functions manipulate and analyze text data.
Returns string
LENGTH() LENGTH(string) SELECT LENGTH('hello'); → 5
length
Example:
AGE Example:
4. Conditional Functions
Conditional functions return values based on specific conditions.
CASE Expression
SELECT name,
CASE
WHEN salary > 60000 THEN 'High'
ELSE 'Low'
END AS salary_level
FROM employee;
5. Window Functions
Window functions perform calculations across sets of rows related to the current row.
Example:
Tip: Practice these functions with your own tables to gain confidence and understanding.
⁂
1. DATEADD
Purpose: Adds an interval to a date.
PostgreSQL Syntax:
Example:
2. DATEPART
Purpose: Extracts part of a date (year, month, day, etc.).
PostgreSQL Syntax:
Example:
SELECT EXTRACT(YEAR FROM CURRENT_DATE) AS year;
SELECT EXTRACT(MONTH FROM '2025-04-25'::date) AS month;
3. DATEDIFF
Purpose: Calculates the difference between two dates.
PostgreSQL Syntax:
Example:
4. FORMAT
Purpose: Formats values as strings.
PostgreSQL Syntax:
Example:
Example:
SELECT (date_trunc('month', '2025-04-25'::date) + INTERVAL '1 month - 1 day')::date AS en
-- Result: 2025-04-30
This is the standard workaround since PostgreSQL does not have a direct EOMONTH()
function [10] [11] [12] .
Example:
Example:
This ranks employees within each department by salary.
Summary Table
PostgreSQL
Function Example
Equivalent
Note:
PostgreSQL does not have direct equivalents for some SQL Server functions, but the above
workarounds are standard and widely used.
For more details, refer to the [official PostgreSQL date/time functions documentation] [11] .
⁂
1. https://neon.tech/postgresql/postgresql-getting-started
2. https://www.datacamp.com/tutorial/beginners-introduction-postgresql
3. https://www.geeksforgeeks.org/postgresql-tutorial/
4. https://www.tutorialspoint.com/postgresql/index.htm
5. https://www.w3schools.com/postgresql/
6. https://neon.tech/postgresql/postgresql-aggregate-functions
7. https://www.slingacademy.com/article/postgresql-aggregation-sum-avg-min-max/
8. https://www.commandprompt.com/education/postgresql-conditional-expressions-explained-with-exam
ples/
9. https://neon.tech/postgresql/postgresql-tutorial/postgresql-coalesce
10. https://stackoverflow.com/questions/47785320/eomonth-equivalent-in-postgresql
11. https://www.postgresql.org/docs/current/functions-datetime.html
12. https://www.sherloqdata.io/sql-functions/eomonth-in-sql
PostgreSQL Advanced SQL Notes
Window Functions
Window functions perform calculations across sets of rows related to the current row, without collapsing rows like
aggregate functions do. They require the OVER clause and can include PARTITION BY, ORDER BY, and a frame clause.
Syntax:
• Frame clause: Limits the rows within the partition for the function.
ROW_NUMBER() Row number within ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary
partition DESC)
RANK() Rank with gaps within RANK() OVER (ORDER BY score DESC)
partition
FIRST_VALUE() Value from first row in FIRST_VALUE(salary) OVER (PARTITION BY dept ORDER BY
window salary)
LAST_VALUE() Value from last row in LAST_VALUE(salary) OVER (PARTITION BY dept ORDER BY
window salary)
Example Usage:
Subqueries
PostgreSQL supports several types of subqueries, each with its own syntax, example, and usage scenario:
1. Scalar Subquery
• Syntax:
SELECT column1
FROM table1
WHERE column2 = (SELECT column3 FROM table2 WHERE condition);
• Example:
• Usage: Used when you need to compare a value in the outer query to a single value returned by the subquery
(e.g., maximum, minimum, or specific value lookup)[1][2].
2. Multi-row Subquery
• Syntax:
SELECT column1
FROM table1
WHERE column2 IN (SELECT column3 FROM table2 WHERE condition);
• Example:
SELECT * FROM COMPANY WHERE ID IN (SELECT ID FROM COMPANY WHERE SALARY > 45000);
• Usage: Used with operators like IN, ANY, SOME, or ALL to compare a value to a set of values returned by the
subquery[1][3][4].
3. Row Subquery
• Syntax:
SELECT column1
FROM table1
WHERE (column2, column3) = (SELECT column4, column5 FROM table2 WHERE condition);
• Example:
SELECT first_name
FROM employees
WHERE ROW(department_id, manager_id) = (
SELECT department_id, manager_id
FROM departments
WHERE location_id = 1800
);
• Usage: Used when you need to compare multiple columns at once between tables[2].
4. Correlated Subquery
• Definition: References columns from the outer query; executed once for each row processed by the outer query.
• Syntax:
SELECT column1
FROM table1 t1
WHERE column2 = (
SELECT MAX(column3)
FROM table2 t2
WHERE t2.column4 = t1.column4
);
• Example:
SELECT name
FROM employees e1
WHERE salary = (
SELECT MAX(salary)
FROM employees e2
WHERE e2.department_id = e1.department_id
);
• Usage: Useful for queries where the subquery’s result depends on the current row of the outer query[1].
• Syntax:
SELECT alias.*
FROM (SELECT column1, column2 FROM table1 WHERE condition) AS alias
WHERE alias.column1 > value;
• Example:
• Scalar subqueries must return only one row and one column; otherwise, an error occurs.
• Multi-row subqueries should be used with operators that accept multiple values (IN, ANY, etc.).
• Subqueries cannot use ORDER BY unless combined with LIMIT/OFFSET or used in the outer query[4].
Summary Table
Scalar 1 row, 1 column WHERE column = (SELECT MAX(column) FROM ...) =, <, >, <=, >=
Multi-row Multiple rows, 1 WHERE column IN (SELECT column FROM ...) IN, ANY,
column SOME, ALL
Row 1 row, multiple WHERE (col1, col2) = (SELECT col3, col4 FROM ...) =
columns
Correlated Varies WHERE column = (SELECT MAX(column) FROM ... =, <, >, etc.
WHERE ... = outer_table.column)
FROM Clause Table-like SELECT * FROM (SELECT ... FROM ...) AS alias WHERE N/A
(Derived) ...
These subquery types allow you to write flexible and powerful SQL statements in PostgreSQL[1][3][2][4].
SELECT name FROM employees WHERE department_id = (SELECT id FROM departments WHERE name = 'HR');
SELECT name FROM employees WHERE department_id IN (SELECT id FROM departments WHERE location =
'NY');
SELECT name FROM employees WHERE EXISTS (SELECT 1 FROM salaries WHERE employees.id =
salaries.emp_id AND amount > 100000);
A CTE provides a temporary result set that can be referenced within a SELECT, INSERT, UPDATE, or DELETE statement.
Syntax:
WITH cte_name AS (
SELECT ...
)
SELECT * FROM cte_name;
Example:
WITH high_earners AS (
SELECT id, salary FROM employees WHERE salary > 100000
)
SELECT * FROM high_earners;
Recursive CTE
Syntax:
HAVING Clause
The HAVING clause is used to filter groups after aggregation, unlike WHERE which filters rows before aggregation.
Syntax:
Procedures are routines that can perform operations such as inserts, updates, and control transactions. They can accept
parameters, have output variables, and be called with or without arguments.
Encryption:
• PostgreSQL does not natively support procedure encryption. You can restrict access using roles and permissions.
Returns value No (can use OUT parameters) Yes (must return a value)
These notes cover advanced SQL features in PostgreSQL, including window functions, subqueries, CTEs (including
recursive), the HAVING clause, and stored procedures with examples and usage details.[1][2][3][4][5]
1. https://neon.tech/postgresql/postgresql-window-function
2. https://www.postgresql.org/docs/current/functions-window.html
3. https://www.timescale.com/learn/postgresql-window-functions
4. https://www.draxlr.com/blogs/common-table-expressions-and-its-example-in-postgresql/
5. https://www.stratascratch.com/blog/learn-to-use-a-recursive-cte-in-sql-query/