0% found this document useful (0 votes)
137 views8 pages

Advanced SQL Cheat Sheet 1736497122

This document is an advanced SQL cheat sheet covering various topics such as subqueries, common table expressions (CTEs), window functions, joins, indexing, transactions, and triggers. It provides example queries for each topic to illustrate their usage. The content is designed to assist users in writing complex SQL queries and optimizing database interactions.

Uploaded by

6ynzh6c977
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)
137 views8 pages

Advanced SQL Cheat Sheet 1736497122

This document is an advanced SQL cheat sheet covering various topics such as subqueries, common table expressions (CTEs), window functions, joins, indexing, transactions, and triggers. It provides example queries for each topic to illustrate their usage. The content is designed to assist users in writing complex SQL queries and optimizing database interactions.

Uploaded by

6ynzh6c977
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/ 8

ADVANCED SQL

CHEAT SHEET

SQL CHEAT SHEET


Subqueries and Nested Queries:

Subqueries: SQL queries embedded within other queries. They can be used in
SELECT, WHERE, and HAVING clauses.

Query:

SELECT name,
(SELECT MAX(salary)
FROM employees) AS max_salary
FROM employees;

Correlated Subqueries: A subquery that depends on the outer query for its values.
Query:

SELECT name, salary


FROM employees e
WHERE salary > ( SELECT AVG(salary)
FROM employees
WHERE department_id = e.department_id );

Query:

SELECT name
FROM employees
WHERE department_id = ( SELECT department_id
FROM departments
WHERE name = 'HR' );

Scalar Subqueries: A subquery that returns a single value.

Query:
SELECT employee_id, name,
( SELECT COUNT(*)
FROM orders
WHERE employee_id = e.employee_id) AS order_count
FROM employees e;
Common Table Expressions (CTEs):

CTEs allow temporary result sets to be referenced within the execution scope of a SELECT,
INSERT, UPDATE, or DELETE statement. Useful for organizing complex queries.

Query:
WITH department_salary AS (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
)
SELECT department_id, avg_salary
FROM department_salary;

Recursive CTEs: Useful for hierarchical or tree-like data structures (e.g., org charts, file
systems).

Query:

WITH RECURSIVE employee_hierarchy AS (


SELECT employee_id, manager_id, name
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.manager_id, e.name
FROM employees e
JOIN employee_hierarchy eh
ON e.manager_id = eh.employee_id
)
SELECT * FROM employee_hierarchy;
Window Functions (Analytic Functions):

ROW_NUMBER(): Assigns a unique number to each row within a result set.

Query:
SELECT name, salary,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num
FROM employees;

RANK() and DENSE_RANK(): Provide ranking numbers, handling ties in different ways.

Query:
SELECT name, salary,
RANK() OVER (ORDER BY salary DESC) AS rank
FROM employees;

NTILE(): Divides rows into a specified number of buckets.

Query:
SELECT name, salary,
NTILE(4) OVER (ORDER BY salary DESC) AS quartile
FROM employees;

LEAD() and LAG(): Allow access to subsequent and previous rows without using self-joins.

Query:
SELECT name, salary,
LAG(salary, 1) OVER (ORDER BY salary DESC) AS previous_salary,
LEAD(salary, 1) OVER (ORDER BY salary DESC) AS next_salary
FROM employees;
Joins and Advanced Join Types:
INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN: Basic joins.

Query:

SELECT e.name, d.name


FROM employees e
INNER JOIN departments d ON e.department_id = d.department_id;

Query:

SELECT e.name, d.name


FROM employees e
LEFT JOIN departments d ON e.department_id = d.department_id;

SELF JOIN: A join where a table is joined to itself, typically used for hierarchical data.

Query:
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.employee_id;

CROSS JOIN: Produces the Cartesian product of two tables.

Query:
SELECT e.name, d.name
FROM employees e
CROSS JOIN departments d;

NATURAL JOIN: Automatically joins tables based on columns with the same name.

Query:
SELECT name, department_name
FROM employees
NATURAL JOIN departments;
Indexing and Query Optimization:

Index Types: B-tree, Hash, GiST, and Full-text indexes.

Query:
CREATE INDEX idx_employee_name
ON employees (name);

Composite Indexes: Indexes on multiple columns.

Query:
CREATE INDEX idx_employee_salary_dept
ON employees (salary, department_id);

EXPLAIN: Used to analyze query execution plans, identify bottlenecks, and optimize queries.

Query:
EXPLAIN SELECT name
FROM employees
WHERE salary > 50000;

Query Optimization Techniques: Avoiding SELECT *, using joins efficiently, and minimizing
Transactions and Concurrency Control:

ACID Properties: Atomicity, Consistency, Isolation, Durability.


Transaction Management: Using BEGIN TRANSACTION, COMMIT, and ROLLBACK.

Query:

BEGIN TRANSACTION;
-- Your SQL queries
COMMIT; -- Or ROLLBACK;

Locking Mechanisms: Pessimistic locking (e.g., SELECT FOR UPDATE) vs. Optimistic locking.

Query:

SELECT *
FROM employees
WHERE employee_id = 1 FOR UPDATE;
Triggers:

DML Triggers: Triggers that execute on insert, update, or delete operations.


INSTEAD OF Triggers: Used to replace the standard actions of an insert, update, or delete
statement.
AFTER Triggers: Executed after the operation has been completed.

Query:

CREATE TRIGGER after_employee_update


AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
INSERT INTO audit_log (action, employee_id)
VALUES ('Update', OLD.employee_id);
END;

BEFORE Triggers: Executed before the operation is executed.

Query:
CREATE TRIGGER before_employee_insert
BEFORE INSERT ON employees
FOR EACH ROW
SET NEW.created_at = NOW();

Thank You

You might also like