Databases 8 min read

10 Must‑Know Advanced SQL Tricks to Boost Your Development Efficiency

This article presents ten essential advanced SQL techniques—including EXPLAIN, window functions, CTEs, bulk operations, index optimization, transactions, JSON handling, temporary tables, proper NULL handling, and recursive queries—to help developers write more efficient, maintainable, and powerful database code.

php Courses
php Courses
php Courses
10 Must‑Know Advanced SQL Tricks to Boost Your Development Efficiency

SQL (Structured Query Language) is one of the most powerful and widely used tools in a developer's toolbox. Whether you are a backend developer, data analyst, or full‑stack engineer, mastering a few advanced SQL techniques can significantly improve your productivity and code quality. Below are key SQL tricks every developer should know.

1. Understanding the EXPLAIN command

EXPLAIN

is the starting point for query performance optimization. It shows the execution path the database takes, helping you identify performance bottlenecks. EXPLAIN SELECT * FROM users WHERE age > 30; Analyzing the output lets you:

Check whether appropriate indexes are used

Identify full table scans

Understand the order of join operations

Estimate query cost

2. Mastering Window Functions

Window functions allow you to perform calculations over a "window" of rows without reducing the result set.

SELECT
    name,
    department,
    salary,
    AVG(salary) OVER (PARTITION BY department) AS avg_department_salary,
    RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dept_rank
FROM employees;

Common window functions include: ROW_NUMBER(): assign a unique sequential number to each row RANK(): assign ranking with ties receiving the same rank DENSE_RANK(): similar to RANK but without gaps LEAD() / LAG(): access values from following or preceding rows

3. Using CTEs (Common Table Expressions) for Readability

CTEs with the WITH clause create temporary result sets, making complex queries easier to read and maintain.

WITH high_value_customers AS (
    SELECT customer_id, SUM(amount) AS total_spent
    FROM orders
    GROUP BY customer_id
    HAVING SUM(amount) > 10000
)
SELECT c.name, h.total_spent
FROM customers c
JOIN high_value_customers h ON c.id = h.customer_id;

CTEs are especially useful for:

Recursive queries (e.g., organizational charts)

Breaking down complex queries

Referencing the same subquery multiple times

4. Bulk Insert and Update Techniques

Bulk inserts are far more efficient than inserting rows one by one:

INSERT INTO products (name, price, category)
VALUES
    ('Product A', 19.99, 'Electronics'),
    ('Product B', 29.99, 'Home'),
    ('Product C', 9.99, 'Office');

Bulk updates can be performed with CASE expressions:

UPDATE employees
SET salary = CASE
    WHEN performance_rating = 'Excellent' THEN salary * 1.10
    WHEN performance_rating = 'Good' THEN salary * 1.05
    ELSE salary * 1.02
END;

5. Index Optimization

Understanding and correctly using indexes is key to SQL performance:

Composite index: CREATE INDEX idx_name_age ON users(name, age); Partial index:

CREATE INDEX idx_active_users ON users(id) WHERE is_active = true;

Covering index:

CREATE INDEX idx_order_info ON orders(customer_id, order_date, total_amount);

6. Transactions for Data Integrity

Transactions ensure a series of operations either all succeed or all fail:

BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
-- If any statement fails
ROLLBACK;
-- If all succeed
COMMIT;

Remember the ACID properties: Atomicity, Consistency, Isolation, Durability.

7. JSON Handling in Modern SQL Databases

Many modern databases (e.g., PostgreSQL, MySQL 5.7+) support JSON data types and functions:

-- Extract JSON field
SELECT data->>'name' AS name FROM users;

-- Query JSON array
SELECT * FROM products WHERE JSON_CONTAINS(categories, '"Electronics"');

-- Update JSON field
UPDATE users
SET profile = JSON_SET(profile, '$.address.city', 'New York')
WHERE id = 1;

8. Temporary Tables and Table Variables

Temporary tables are useful for handling intermediate results:

-- Create temporary table
CREATE TEMPORARY TABLE temp_high_sales AS
SELECT product_id, SUM(amount) AS total_sales
FROM sales
GROUP BY product_id
HAVING SUM(amount) > 10000;

-- Use temporary table
SELECT p.name, t.total_sales
FROM products p
JOIN temp_high_sales t ON p.id = t.product_id;

9. Proper NULL Handling

NULL requires special handling in SQL:

-- Provide default with COALESCE
SELECT name, COALESCE(phone, 'N/A') AS phone FROM customers;

-- Avoid division by zero with NULLIF
SELECT total / NULLIF(count, 0) AS average FROM stats;

-- Test for NULL correctly
SELECT * FROM users WHERE phone IS NULL;

10. Recursive Queries

Recursive CTEs can process hierarchical data:

WITH RECURSIVE org_hierarchy AS (
    -- Base query: top‑level managers
    SELECT id, name, manager_id, 1 AS level
    FROM employees
    WHERE manager_id IS NULL

    UNION ALL

    -- Recursive query: subordinates
    SELECT e.id, e.name, e.manager_id, h.level + 1
    FROM employees e
    JOIN org_hierarchy h ON e.manager_id = h.id
)
SELECT *
FROM org_hierarchy
ORDER BY level, name;

Mastering these SQL techniques will transform you from a developer who can write SQL into one who truly masters it, enabling you to write more efficient, maintainable database code and solve complex data problems.

SQLdatabase optimizationIndexestransactionsWindow FunctionsCTEAdvanced Queries
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.