0% found this document useful (0 votes)
1 views1 page

PostgreSQL Mastery Cheat Sheet

The document is a comprehensive cheat sheet for mastering PostgreSQL, covering basic SQL queries, aggregation functions, data filtering, sorting, grouping, joining tables, and advanced SQL techniques. It includes examples of SQL commands for various operations such as selecting data, counting records, and using window functions. Additionally, it provides insights into string functions, date and time functions, and recursive queries.

Uploaded by

amurao.frances
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views1 page

PostgreSQL Mastery Cheat Sheet

The document is a comprehensive cheat sheet for mastering PostgreSQL, covering basic SQL queries, aggregation functions, data filtering, sorting, grouping, joining tables, and advanced SQL techniques. It includes examples of SQL commands for various operations such as selecting data, counting records, and using window functions. Additionally, it provides insights into string functions, date and time functions, and recursive queries.

Uploaded by

amurao.frances
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

dataford.

io

PostgreSQL Mastery Cheat Sheet


1. Basic SQL Queries 2. Aggregation Functions

Select All Data Count Records


Query to retrieve all columns from the users table. Count the total number of orders from the orders table.

1
SELECT * 1
SELECT COUNT(*) 

2 FROM users; 2 FROM orders;

Select Specific Column Sum Column Values


Retrieve only the first_name column from the customers table. Calculate the total sales from the sales table.

1
SELECT first_name 1
SELECT SUM(sale_amount) 

2 FROM customers; 2 FROM sales;

Filter Records by Condition Find Maximum Value


Fetch all users where the first name is "john" from the user_details table. Retrieve the highest salary from the salaries table.

1
SELECT * 
1
SELECT MAX(salary) 

2
FROM user_details 
2 FROM salaries;
3 WHERE first_name = 'john';

Find Minimum Value


Sort Records
Retrieve the lowest score from the exam_scores table.
Get all product names sorted by price in descending order from the products
table. 1
SELECT MIN(score) 

2 FROM exam_scores;
1
SELECT product_name 

2
FROM products 

3 ORDER BY price DESC;


Calculate Average
Get the average order amount from the orders table.
Filter Data by Range
1
SELECT AVG(order_amount) 

Retrieve all employees whose age is between 25 and 40 from the employees 2 FROM orders;
table.

1
SELECT * 

2
FROM employees 

3 WHERE age BETWEEN 25 AND 40;


3. Grouping

Find Null Values Group by and Count


Select users from the customers table who don't have an email address. Count the number of users per country from the users table.

1
SELECT *
1
SELECT country, COUNT(*) 

2
FROM customers
2
FROM users 

3 WHERE email IS NULL; 3 GROUP BY country;

Remove Duplicate Entries Group by and Sum


Fetch unique departments from the departments table. Calculate the total sales per product category from the product_sales table.

1
SELECT DISTINCT department 
1
SELECT category, SUM(sales) 

2
FROM departments;
2
FROM product_sales 

3 GROUP BY category;

Group by and Filter (HAVING)


4. Joining Tables Get departments where the total salary is greater than $1,000,000.

1
SELECT department, SUM(salary)

Inner Join 2
FROM salaries

Retrieve employee names along with their department names. 3


GROUP BY department

4 HAVING SUM(salary) > 1000000;


1
SELECT e.first_name, d.department_name 

2
FROM employees e 

3
INNER JOIN departments d 

4 ON e.department_id = d.department_id;
5. Subqueries
Left Join
Subquery in WHERE
Get all employees and their assigned projects, even if some employees don’t have
projects. Fetch all products with a price greater than the average price.

1
SELECT e.first_name, p.project_name 
1
SELECT * 

2
FROM employees e 
2
FROM products 

3
LEFT JOIN projects p 
3 WHERE price > (SELECT AVG(price) FROM products);
4 ON e.employee_id = p.employee_id;

Right Join Subquery in SELECT

List all projects and the employees assigned to them, including projects without Retrieve employee names and their corresponding department names using a
employees. subquery.

1
SELECT p.project_name, e.first_name 
1
SELECT first_name,

2
FROM projects p 
2
(SELECT department_name

3
RIGHT JOIN employees e 
3
FROM departments

4 ON p.project_id = e.project_id; 4
WHERE department_id = employees.department_id) AS
5
department

6 FROM employees;
Full Outer Join
Retrieve all employees and all projects, including those with no matching records.
Subquery in FROM
1
SELECT e.first_name, p.project_name 
Find the total sales per product using a subquery.
2
FROM employees e 

3
FULL OUTER JOIN projects p 
1
SELECT department, SUM(salary)

4 ON e.employee_id = p.employee_id; 2
FROM salaries

3
GROUP BY department

4 HAVING SUM(salary) > 1000000;

6. Window Functions
Rank Over Partition 7. String Functions
Rank products based on sales within each category.
Concatenate Strings
1
SELECT product_id, category_id, sales_amount, 

Combine first name and last name to display full name.


2
RANK() OVER (PARTITION BY category_id ORDER BY
3
sales_amount DESC) AS rank 
1
SELECT CONCAT(first_name, ' ', last_name) AS full_name 

4 FROM products; 2
FROM users;

Running Total
Calculate the cumulative sales for each product over time. String Length
Get the length of the product name.
1
SELECT product_id, sale_date, sales_amount, 

2
SUM(sales_amount) OVER (ORDER BY sale_date) AS 1
SELECT LENGTH(product_name) 

3
running_total 
2
FROM products;
4 FROM sales;

Lag Function
Substring
Find the previous order amount for each user.
Extract the first 3 characters of the product name.
1
SELECT user_id, order_date, order_amount, 

2
1
SELECT SUBSTRING(product_name, 1, 3) 

LAG(order_amount, 1) OVER (PARTITION BY user_id


3
2
FROM products;
ORDER BY order_date) AS previous_order 

4 FROM orders;

Upper and Lower Case

8. Date and Time Functions


Display customer names in uppercase.

1
SELECT UPPER(customer_name) 

2
FROM customers;
Current Date
Retrieve all users who joined today.

1
SELECT * 

2
FROM users 

3 WHERE join_date = CURRENT_DATE; 9. Advanced SQL

Case Statements
Extract Year
Display gender as 'M' or 'F' based on the gender column.
Get the year from the join_date column.
1
SELECT first_name, last_name, 

1
SELECT EXTRACT(YEAR FROM join_date) 
2
CASE 

2
FROM users; 3
WHEN gender = 'male' THEN 'M' 

4
WHEN gender = 'female' THEN 'F' 

5
END AS gender_abbr 

6 FROM users;
Date Difference
Calculate the number of days between order_date and today.
Coalesce Function
1
SELECT age(CURRENT_DATE, order_date) 
Replace null values in the address column with 'unknown'.
2
FROM orders;
1
SELECT COALESCE(address, 'unknown') 

2
FROM customers;

Add Date Interval


Find all users who signed up in the last 30 days.
Casting and Conversion
1
SELECT * 
Convert order_amount to a decimal value with 2 decimal places.
2
FROM users 

3 WHERE join_date > CURRENT_DATE - INTERVAL '30 days'; 1


SELECT CAST(order_amount AS DECIMAL(10, 2)) 

2
FROM orders;

Recursive Query

Practice Interview Questions on Dataford.io Generate a sequence of numbers from 1 to 10.

1
WITH numbers AS (

2
SELECT 1 AS number

3
UNION ALL

4
SELECT number + 1 

5
FROM numbers 

6
WHERE number < 10

7
)

8
SELECT number 

9
FROM numbers;

Cross Join Example


Retrieve a combination of every employee with every project.

1
SELECT e.first_name, p.project_name

2
FROM employees e

3 CROSS JOIN projects p;

Cross Join with Filter


Perform a cross join between employees and projects, but only show combinations
where the employee's department matches the project's department.

1
SELECT e.first_name, p.project_name

2
FROM employees e

3
CROSS JOIN projects p

4 WHERE e.department_id = p.department_id;

You might also like