You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
UPDATE employees
SET salary = salary *1.10WHERE department ='HR';
DELETE: Remove rows.
DELETEFROM employees WHERE age <25;
11. Advanced SQL
Case Statements: Conditional logic.
SELECT name,
CASE
WHEN salary >80000 THEN 'High'
WHEN salary BETWEEN 50000AND80000 THEN 'Medium'
ELSE 'Low'
END AS salary_category
FROM employees;
UNION: Combine results of two queries.
SELECT name FROM employees WHERE department ='HR'UNIONSELECT name FROM employees WHERE salary >60000;
EXISTS: Check for existence of rows in a subquery.
SELECT*FROM employees
WHERE EXISTS (SELECT1FROM departments WHEREdepartments.department_id=employees.department_idAND location ='NYC');
Recursive CTEs: Example for hierarchical data.
WITH RECURSIVE EmployeeHierarchy AS (
SELECT employee_id, name, manager_id
FROM employees
WHERE manager_id IS NULLUNION ALLSELECTe.employee_id, e.name, e.manager_idFROM employees e
INNER JOIN EmployeeHierarchy eh
ONe.manager_id=eh.employee_id
)
SELECT*FROM EmployeeHierarchy;
12. Indexes and Performance
Use indexes to speed up queries.
CREATEINDEXidx_salaryON employees(salary);
Avoid using SELECT * in production.
Analyze query plans for optimization: EXPLAIN or EXPLAIN ANALYZE.
13. Practice Patterns for LeetCode SQL
Self-Joins: Compare rows in the same table.
SELECTa.id, b.idFROM employees a, employees b
WHEREa.salary>b.salaryANDa.department=b.department;
Ranking Problems: Use ROW_NUMBER() or RANK().
SELECT name, salary, RANK() OVER (ORDER BY salary DESC) AS rank
FROM employees;
Top-N Queries: Use LIMIT with ORDER BY.
SELECT name, salary FROM employees ORDER BY salary DESCLIMIT5;
Gaps and Islands: Use window functions and GROUP BY.
SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department;
14. Business Analyst-Specific SQL
Revenue analysis:
SELECT product_category, SUM(revenue) AS total_revenue
FROM sales_data
GROUP BY product_category
ORDER BY total_revenue DESC;
Customer segmentation:
SELECT customer_id, COUNT(*) AS purchase_count
FROM purchases
GROUP BY customer_id
HAVINGCOUNT(*) >5;
Monthly trend analysis:
SELECT DATE_TRUNC('month', sale_date) AS month, SUM(revenue) AS total_revenue
FROM sales
GROUP BY DATE_TRUNC('month', sale_date)
ORDER BY month;
Tips for LeetCode SQL Challenges
Read the problem carefully, focusing on constraints.