A subquery, also known as an inner query or nested query, is a query within another SQL query.
It allows you perform complex queries by using the result of one query as a condition in another query.
SELELCT name FROM employees WHERE salary = (SELECT MAX(salary) FROM employees);SELECT name FROM employees WHERE department_id IN (SELECT department_id FROM departments WHERE location = 'New York');SELECT e1.name, e1.salary FROM employees e1 WHERE e1.salary > (SELECT AVG(e2.salary) FROM employees e2 WHERE e1.department_id = e2.department_id);SELECT name, (SELECT MAX(salary) FROM employees WHERE department_id = e.department_id) AS max_salary FROM employees e;
SELECT name FROM employees WHERE department_id = (SELECT department_id FROM departments WHERE name = 'Sales');
SELECT AVG(salary) FROM (SELECT salary FROM employees WHERE department_id = 10);
Window functions perform calculations across a set of table rows that are somehow related to current row. They are similar to aggregate funcions, but unlike aggregate functions, they do not cause rows to become grouped into a single output row,
SELECT column,
window_function() OVER (PARTITION BY column1 ORDER-BY column2)
From table;
SELECT name, department_id, salary,
ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS row_num
FROM employees;
This query assigns a unique rank to each row within each department based on the salary.
SELECT department_id, salary,
SUM(salary) OVER (PARTITION BY department_id) AS total_salary
FROM employees;
This query calculated the total salary for each department without collapsing the rows.
SELECT name, department_id, salary,
SUM(salary) OVER (PARTITION BY department_id ORDER BY salary ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total
From employees;This query calculated a running total of salaries within each department