Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

From sales(region, quarter, amount) with quarter values Q1 to Q4, produce one row per region with columns q1 to q4. Write it portably, then mention engine-specific options.

The portable way is conditional aggregation: SELECT region, SUM(CASE WHEN quarter = 'Q1' THEN amount END) AS q1, and the same for q2 to q4, FROM sales GROUP BY region. PostgreSQL offers the shorter SUM(amount) FILTER (WHERE quarter = 'Q1'), and engine-specific tools such as PostgreSQL's crosstab() or the PIVOT clause in SQL Server and Oracle exist, but all of them need the column list when the query is written. Missing quarters give NULL, which COALESCE turns into 0, and truly dynamic columns need generated SQL or pivoting in the application or reporting tool.

Why this question is asked

Pivoting turns rows into columns: instead of one row per region and quarter, one row per region with a column per quarter. It is how people read reports, and spreadsheets do it with a click, so stakeholders expect it from every report. Interviewers ask for it because the portable technique, conditional aggregation, shows a solid grasp of GROUP BY and CASE, and because the limits of pivoting, especially dynamic columns, come up in every reporting project. In this answer, we will look at the data before and after, write the pivot portably, write it again with PostgreSQL's FILTER clause, look at crosstab and PIVOT, handle missing quarters, and discuss what to do when the columns are not known in advance.

1The Data Before and After

Our sales table is in long format: one row per region per quarter, possibly several rows per quarter if sales are recorded per order. We want wide format: one row per region and one column per quarter.

Long rows become one wide row per region
regionq1q2q3q4
EU120135110160
US200210NULL (no Q3 rows)240
Source rows look like (EU, Q1, 70), (EU, Q1, 50), (EU, Q2, 135) and so on; EU's Q1 total is 70 + 50 = 120.

2The Portable Way: Conditional Aggregation

The trick is to group by region, which gives one output row per region, and then compute each quarter's column with an aggregate that only counts that quarter's rows. A CASE expression inside SUM returns the amount for rows of the wanted quarter and NULL otherwise, and SUM ignores NULLs.

SQL
SELECT region,
SUM(CASE WHEN quarter = 'Q1' THEN amount END) AS q1,
SUM(CASE WHEN quarter = 'Q2' THEN amount END) AS q2,
SUM(CASE WHEN quarter = 'Q3' THEN amount END) AS q3,
SUM(CASE WHEN quarter = 'Q4' THEN amount END) AS q4
FROM sales
GROUP BY region
ORDER BY region;
-- EU | 120 | 135 | 110 | 160
-- US | 200 | 210 | NULL | 240

This runs on PostgreSQL, MySQL, SQL Server, Oracle and practically every other SQL engine. It reads the table once, and each row contributes to exactly one of the four sums. If we need several measures per quarter, such as revenue and order count, we add more conditional aggregates, for example COUNT(CASE WHEN quarter = 'Q1' THEN 1 END) AS q1_orders, all in the same single pass.

3The PostgreSQL Way: FILTER

PostgreSQL supports the SQL standard FILTER clause on aggregates, which says the same thing more directly: aggregate only the rows that match this condition.

SQL
SELECT region,
SUM(amount) FILTER (WHERE quarter = 'Q1') AS q1,
SUM(amount) FILTER (WHERE quarter = 'Q2') AS q2,
SUM(amount) FILTER (WHERE quarter = 'Q3') AS q3,
SUM(amount) FILTER (WHERE quarter = 'Q4') AS q4
FROM sales
GROUP BY region;
-- same result as above

FILTER is easier to read, especially with COUNT, where COUNT(*) FILTER (WHERE quarter = 'Q1') is clearer than COUNT(CASE ... THEN 1 END). It is not available in MySQL 8.4 or SQL Server, so for portable code we stay with CASE.

4Engine-Specific Pivot Tools

Some engines have dedicated syntax. PostgreSQL's tablefunc extension provides crosstab(), which takes a query returning (row key, category, value) and spreads the categories into columns. SQL Server and Oracle have a PIVOT clause.

SQL
-- PostgreSQL: CREATE EXTENSION tablefunc;
SELECT *
FROM crosstab(
$$SELECT region, quarter, SUM(amount) FROM sales GROUP BY 1, 2 ORDER BY 1, 2$$,
$$VALUES ('Q1'), ('Q2'), ('Q3'), ('Q4')$$
) AS ct(region text, q1 numeric, q2 numeric, q3 numeric, q4 numeric);
-- SQL Server:
SELECT region, [Q1] AS q1, [Q2] AS q2, [Q3] AS q3, [Q4] AS q4
FROM (SELECT region, quarter, amount FROM sales) s
PIVOT (SUM(amount) FOR quarter IN ([Q1], [Q2], [Q3], [Q4])) p;

Notice that every one of them still needs the output columns listed in the query: crosstab needs the column definition list after AS ct, and PIVOT needs the IN list. That is not an oversight. A SQL query must have a fixed set of result columns known when it is planned, so no single static SQL statement can produce 'one column per quarter that happens to exist'. The second form of crosstab, with the category query, also places values in the right column when some regions are missing a quarter, which the one-argument form does not.

5Missing Quarters: NULL or 0

The US had no Q3 rows, so SUM over zero matching rows returned NULL, not 0. That is SQL's way of saying 'there was nothing to add'. In a report, NULL usually shows as an empty cell, which may be right ('no data') or wrong ('zero sales'), depending on what the report means.

SQL
SELECT region,
COALESCE(SUM(CASE WHEN quarter = 'Q3' THEN amount END), 0) AS q3
FROM sales GROUP BY region;
-- EU | 110
-- US | 0

COALESCE returns its first non-NULL argument, so it turns NULL into 0. Writing ELSE 0 inside the CASE does the same for conditional aggregation. I prefer to decide this with the report owner, because a quarter that has not happened yet and a quarter with zero sales are different facts.

6When the Columns Are Not Known in Advance

Quarters are a fixed set, so writing four columns is fine. But if the columns are, say, product categories that change monthly, a static query cannot keep up. There are two sound approaches. The first is to generate the SQL: the application first queries SELECT DISTINCT category, then builds the conditional aggregation with one column per category, using a whitelist or proper identifier quoting so that category names cannot inject SQL. The second, usually better, is to return the long format from the database and pivot in the application or the reporting tool, which are built for it: a Java map from region to a map from category to amount, or the pivot feature of the BI tool.

Returning long format also keeps the API stable, because adding a category adds rows, not columns, and clients do not need to change.

Java
// Pivoting long rows in Java
record SaleRow(String region, String quarter, BigDecimal amount) {}
Map<String, Map<String, BigDecimal>> pivot = rows.stream()
.collect(Collectors.groupingBy(SaleRow::region, TreeMap::new,
Collectors.toMap(SaleRow::quarter, SaleRow::amount, BigDecimal::add, TreeMap::new)));
// {EU={Q1=120, Q2=135, Q3=110, Q4=160}, US={Q1=200, Q2=210, Q4=240}}

7Follow-up questions

Is conditional aggregation slow with many columns?

It reads the table once regardless of the number of columns; each extra column adds a little CPU per row to evaluate its CASE. With dozens of columns it remains a single scan, which is usually far cheaper than joining several subqueries, one per column.

How would you add a total column and a total row?

A total column is just SUM(amount) without a condition in the same SELECT. A total row can come from GROUP BY ROLLUP (region), which adds a row with region NULL holding the grand totals; wrap region in COALESCE(region, 'All') for display.

Does MySQL have PIVOT?

No. MySQL 8.4 has no PIVOT clause and no FILTER clause, so conditional aggregation with CASE, or SUM(IF(quarter = 'Q1', amount, NULL)), is the standard way, and dynamic pivots there are usually built with generated SQL in the application or a prepared statement.

8Conclusion

In this answer, we pivoted sales from one row per region and quarter into one row per region with four quarter columns. Conditional aggregation with SUM(CASE ...) and GROUP BY works on every engine and reads the table once, PostgreSQL's FILTER clause says the same thing more clearly, and crosstab() and PIVOT exist but still need the column list in the query. Missing quarters come out as NULL, which COALESCE can turn into 0, and when the columns are not known in advance we generate the SQL safely or pivot in the application or reporting tool.

What to say in the interviewAbout 80 seconds aloud

Open with

The portable approach is conditional aggregation. I group by region and compute each quarter as its own aggregate: SUM(CASE WHEN quarter equals Q1 THEN amount END) AS q1, and the same for q2, q3 and q4.

Then, if they want more

Each row only contributes to the sum for its quarter, because the CASE returns NULL otherwise and SUM ignores NULLs, so it's one pass over the table and runs on any engine. In PostgreSQL I'd write it more readably with the FILTER clause: SUM(amount) FILTER (WHERE quarter = 'Q1').

There are engine-specific tools, crosstab from the tablefunc extension in PostgreSQL and the PIVOT clause in SQL Server and Oracle, but they all still need the output columns listed in the query, because a SQL statement must have fixed result columns.

Missing quarters come back as NULL rather than zero; I'd agree with the report owner whether that should show as zero and use COALESCE if so.

And if the columns are dynamic, like product categories that change, I'd either generate the SQL from the distinct values with safe identifier handling, or better, return the long format and pivot in the application or the BI tool, which keeps the API stable.

About this answer

Last updated
12 November 2026
Versions it names
MySQL 8.4
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "From sales(region, quarter, amount) with quarter values Q1 to Q4, produce one row per...": https://scrivio-interview-library.netlify.app/databases/advanced-sql/af109ec9a9/