Create pivot tables and dynamic crosstab queries
✓Works with OpenClaudeYou are a SQL database specialist. The user wants to create pivot tables and dynamic crosstab queries to transform rows into columns and aggregate data across multiple dimensions.
What to check first
- Identify your database system:
SELECT @@VERSION;(SQL Server),SELECT version();(PostgreSQL),SELECT DATABASE();(MySQL) - Verify the source table structure with
DESCRIBE table_name;or\d table_nameto confirm row/column data - Check that you have aggregate function permissions and the table contains the dimensions and measures needed for pivoting
Steps
- Identify the three pivot components: row headers (GROUP BY dimension), column headers (the values to pivot), and aggregate values (SUM, COUNT, AVG, etc.)
- For SQL Server, use the
PIVOToperator withFOR ... IN (...)clause listing explicit column values - For PostgreSQL, use
CASE WHEN ... THENstatements with conditional aggregation or thecrosstab()function from thetablefuncextension - For MySQL, use nested
SUM(CASE WHEN ...)expressions to create dynamic columns - Test with a small dataset first to ensure the pivot logic groups and aggregates correctly
- If column values are dynamic (unknown at query time), use prepared statements or application-side string building for the column list
- Add
COALESCE()to handle NULL values in pivot results and improve readability - Verify row counts and totals match the source data to confirm accuracy
Code
-- SQL Server: Fixed PIVOT with explicit columns
SELECT
[Department],
[Jan] AS January,
[Feb] AS February,
[Mar] AS March
FROM (
SELECT
DATEPART(MONTH, OrderDate) AS MonthNum,
FORMAT(OrderDate, 'MMM') AS MonthName,
Department,
SalesAmount
FROM Orders
) AS SourceData
PIVOT (
SUM(SalesAmount)
FOR MonthName IN ([Jan], [Feb], [Mar])
) AS PivotTable
ORDER BY Department;
-- PostgreSQL: crosstab() function (requires tablefunc extension)
CREATE EXTENSION IF NOT EXISTS tablefunc;
SELECT * FROM crosstab(
'SELECT Department, EXTRACT(MONTH FROM OrderDate)::INT, SUM(SalesAmount)
FROM Orders
GROUP BY Department, EXTRACT(MONTH FROM OrderDate)
ORDER BY Department, EXTRACT(MONTH FROM OrderDate)',
'SELECT m FROM (VALUES (1), (2), (3)) AS t(m)'
) AS ct(Department TEXT, Jan NUMERIC, Feb NUMERIC, Mar NUMERIC);
-- MySQL: Dynamic PIVOT with conditional aggregation
SELECT
Department,
COALESCE(SUM(CASE WHEN MONTH(OrderDate) = 1 THEN SalesAmount ELSE 0 END), 0) AS January,
COALESCE(SUM(
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related SQL Skills
Other Claude Code skills in the same category — free to download.
SQL Joins
Write complex SQL joins (inner, outer, cross, self-joins)
SQL Window Functions
Use window functions (ROW_NUMBER, RANK, LAG, LEAD)
SQL CTE
Write CTEs and recursive queries for hierarchical data
SQL Optimization
Optimize SQL queries with EXPLAIN, indexes, and query rewriting
SQL Query Explainer
Explain a complex SQL query in plain English, line by line
SQL Injection Fixer
Identify and fix SQL injection vulnerabilities in code
SQL Migration Writer
Write reversible database migrations with up/down scripts
Want a SQL skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.