Hidden SQL Functions
π΅οΈββοΈ Hidden SQL Functions You Probably Didnβt Know β But Should! π
When it comes to SQL, most developers stick to the basics: SELECT
, JOIN
, GROUP BY
, maybe a CASE
statement here and there. But SQL hides some powerhouse functions that can drastically simplify your queries, speed up performance, and make your code cleaner.
Today, weβll uncover hidden gems across popular databases like MySQL, PostgreSQL, SQL Server, and Oracle β with examples, best use cases, and optimization tips. π‘
πΉ 1. GROUP_CONCAT()
β Merge Rows into a Single String
π¦ Available in: MySQL, MariaDB (PostgreSQL uses STRING_AGG
)
π What it does: Merges multiple rows into a single, comma-separated (or custom delimiter) string.
π» Example (MySQL):
SELECT department_id, GROUP_CONCAT(employee_name ORDER BY employee_name SEPARATOR ', ')
FROM employees
GROUP BY department_id;
π Output:
department_id | employee_names |
---|---|
1 | Alice, Bob, Charlie |
2 | David, Eva |
π― Best use case:
- Generating readable reports
- Exporting aggregated data without doing joins in application code
πΉ 2. STRING_AGG()
β PostgreSQLβs Answer to GROUP_CONCAT
π¦ Available in: PostgreSQL, SQL Server, Oracle 19c+
π» Example (PostgreSQL):
SELECT department_id, STRING_AGG(employee_name, ', ' ORDER BY employee_name)
FROM employees
GROUP BY department_id;
π― Best use case:
- Same as
GROUP_CONCAT()
but in databases that donβt support it - Can handle ordering and custom delimiters efficiently
πΉ 3. LAG()
& LEAD()
β Look Behind and Ahead in Data
π¦ Available in: PostgreSQL, MySQL 8+, SQL Server, Oracle
π What they do:
Allow you to access the previous (LAG
) or next (LEAD
) rowβs value without a self-join.
π» Example (PostgreSQL):
SELECT
employee_name,
hire_date,
LAG(hire_date) OVER (ORDER BY hire_date) AS prev_hire_date,
LEAD(hire_date) OVER (ORDER BY hire_date) AS next_hire_date
FROM employees;
π― Best use case:
- Calculating differences between rows
- Trend analysis in time-series data
πΉ 4. COALESCE()
β First Non-NULL Value Finder
π¦ Available in: MySQL, PostgreSQL, SQL Server, Oracle
π» Example:
SELECT employee_name, COALESCE(phone_number, 'No Phone') AS contact
FROM employees;
π― Best use case:
- Replace NULL values with defaults
- Useful in reporting and user-facing queries
πΉ 5. NULLIF()
β Avoid Divide-by-Zero Errors
π¦ Available in: MySQL, PostgreSQL, SQL Server, Oracle
π» Example:
SELECT sales / NULLIF(target, 0) AS performance_ratio
FROM performance_data;
π― Best use case:
- Safe mathematical operations
- Cleaner alternative to
CASE WHEN target = 0 THEN NULL ...
πΉ 6. WITH RECURSIVE
β Hierarchical & Tree Data
π¦ Available in: PostgreSQL, MySQL 8+, SQL Server (as CTE), Oracle
π» Example (PostgreSQL):
WITH RECURSIVE employee_hierarchy AS (
SELECT id, name, manager_id FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id
FROM employees e
INNER JOIN employee_hierarchy eh ON e.manager_id = eh.id
)
SELECT * FROM employee_hierarchy;
π― Best use case:
- Category trees
- Employee management hierarchies
πΉ 7. RANK()
& DENSE_RANK()
β Smart Ranking Without Messy Subqueries
π¦ Available in: MySQL 8+, PostgreSQL, SQL Server, Oracle
π» Example:
SELECT
employee_name, department_id,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rank_in_dept
FROM employees;
π― Best use case:
- Leaderboards
- Ranking performance per group
πΉ 8. JSON_TABLE()
β Query JSON Like a Table
π¦ Available in: MySQL 8+, Oracle 12c+, SQL Server (OPENJSON), PostgreSQL (jsonb functions)
π» Example (MySQL):
SELECT *
FROM JSON_TABLE(
'[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]',
"$[*]" COLUMNS(
id INT PATH "$.id",
name VARCHAR(50) PATH "$.name"
)
) AS jt;
π― Best use case:
- Extract structured data from JSON directly in SQL
- Useful for hybrid data storage models
π Bonus Functions to Supercharge Your SQL
π‘ Performance Boosters & Time Savers
-
EXPLAIN
β Check query execution plan (All DBs)EXPLAIN SELECT * FROM employees;
Use for: Optimizing queries before they hit production
-
INDEX HINTS
β Force specific index usage (MySQL)SELECT * FROM employees USE INDEX (idx_department) WHERE department_id = 5;
-
FILTER()
β Conditional aggregation (PostgreSQL)SELECT department_id, COUNT(*) FILTER (WHERE salary > 50000) AS high_salary_count FROM employees GROUP BY department_id;
-
UPSERT
(INSERT ... ON CONFLICT
) β Insert or Update in one shot (PostgreSQL, MySQL)INSERT INTO employees (id, name) VALUES (1, 'Alice') ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name;
π Final Thoughts
SQL is far more powerful than most developers realize. By mastering these hidden functions, you can: β Write cleaner queries β Avoid complex joins and subqueries β Improve performance and maintainability
Remember β the less code you write in your app layer for data processing, the faster your app runs. π
© Lakhveer Singh Rajput - Blogs. All Rights Reserved.