Mastering Long SQL Queries
π Mastering Long SQL Queries: Write Like a Pro! π
Writing long SQL queries can be daunting, but with the right techniques and functions, you can craft efficient, readable, and powerful queries. Whether youβre working with MySQL, PostgreSQL, SQL Server, or Oracle, mastering these key functions will take your SQL skills to the next level.
π Essential SQL Functions for Long Queries
Here are 10 powerful functions (available in major databases) that can simplify complex queries:
1. Window Functions (OVER, PARTITION BY) β PostgreSQL, SQL Server, Oracle
π Use Case: Calculate running totals, rankings, or moving averages.
SELECT
employee_id,
salary,
AVG(salary) OVER (PARTITION BY department_id) AS avg_dept_salary
FROM employees;
2. Common Table Expressions (CTEs) β PostgreSQL, SQL Server, MySQL (8.0+), Oracle
π Use Case: Break complex queries into readable chunks.
WITH high_earners AS (
SELECT * FROM employees WHERE salary > 100000
)
SELECT * FROM high_earners WHERE department = 'Engineering';
3. STRING_AGG / GROUP_CONCAT β PostgreSQL (STRING_AGG), MySQL (GROUP_CONCAT)
π Use Case: Concatenate strings from multiple rows.
-- PostgreSQL
SELECT department_id, STRING_AGG(name, ', ') AS employees
FROM employees
GROUP BY department_id;
-- MySQL
SELECT department_id, GROUP_CONCAT(name SEPARATOR ', ') AS employees
FROM employees
GROUP BY department_id;
4. PIVOT / CROSSTAB β SQL Server, Oracle, PostgreSQL (crosstab)
π Use Case: Transform rows into columns for reports.
-- SQL Server
SELECT * FROM (
SELECT year, product, sales FROM sales_data
) AS src
PIVOT (SUM(sales) FOR product IN ([Laptop], [Phone], [Tablet])) AS pvt;
5. COALESCE / NULLIF β All Databases
π Use Case: Handle NULL values gracefully.
SELECT
name,
COALESCE(bonus, 0) AS bonus -- Replace NULL with 0
FROM employees;
6. LAG / LEAD β PostgreSQL, SQL Server, Oracle
π Use Case: Compare current row with previous/next row.
SELECT
date,
revenue,
LAG(revenue, 1) OVER (ORDER BY date) AS prev_day_revenue
FROM daily_sales;
7. JSON Functions β PostgreSQL, MySQL (5.7+), SQL Server (2016+)
π Use Case: Query and manipulate JSON data.
-- PostgreSQL
SELECT
user_id,
json_data->>'email' AS email
FROM users
WHERE json_data->>'status' = 'active';
8. Dynamic SQL (EXECUTE) β SQL Server, PostgreSQL, Oracle
π Use Case: Build queries dynamically for flexibility.
-- SQL Server
DECLARE @sql NVARCHAR(MAX) = 'SELECT * FROM ' + @table_name;
EXEC sp_executesql @sql;
9. FILTER Clause (PostgreSQL)
π Use Case: Apply aggregate functions conditionally.
SELECT
department_id,
AVG(salary) FILTER (WHERE tenure > 5) AS avg_senior_salary
FROM employees
GROUP BY department_id;
10. Recursive CTEs β PostgreSQL, SQL Server, Oracle
π Use Case: Query hierarchical data (org charts, folders).
WITH RECURSIVE org_tree AS (
SELECT id, name, manager_id FROM employees WHERE id = 1 -- CEO
UNION ALL
SELECT e.id, e.name, e.manager_id
FROM employees e
JOIN org_tree ot ON e.manager_id = ot.id
)
SELECT * FROM org_tree;
π‘ Pro Tips for Writing Long SQL Queries Efficiently
β
Use CTEs for Readability β Break down complex logic into named blocks.
β
Format Consistently β Indent, align, and comment for clarity.
β
Optimize Joins β Use EXPLAIN
to check query performance.
β
Avoid SELECT *** β Fetch only necessary columns.
β
**Index Strategically β Ensure joins and WHERE clauses use indexes.
β
Test Incrementally β Build your query step-by-step.
β
Use Temporary Tables β For extremely complex queries, stage intermediate results.
π― Final Thoughts
Writing long SQL queries doesnβt have to be painful! By leveraging CTEs, window functions, and advanced aggregation, you can write clean, efficient, and maintainable SQL.
πΉ Which SQL function do you use most often? Drop a comment below! π
#SQL #Database #DataEngineering #DataScience #TechTips π
© Lakhveer Singh Rajput - Blogs. All Rights Reserved.