Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

A legacy table metrics(day, cpu_avg, mem_avg, disk_avg) must be turned into rows (day, metric, value) for a new charting service. Write the unpivot in PostgreSQL and explain the performance of each approach.

In PostgreSQL, CROSS JOIN LATERAL (VALUES ('cpu', cpu_avg), ('mem', mem_avg), ('disk', disk_avg)) AS v(metric, value) reads the metrics table once and emits three rows per input row. A UNION ALL of three SELECTs is portable but scans the table three times unless the planner is clever; Oracle and SQL Server have UNPIVOT, and MySQL can use UNION ALL or a JSON_TABLE trick. Beyond the query, we should decide whether the wide table stays the source of truth behind a view, or whether storage moves to the long format, which lets us add metrics without a schema change.

Why this question is asked

Charting libraries and time-series tools almost always want long data: one row per timestamp, series name and value. Legacy tables, built for a fixed dashboard, are often wide, with one column per metric. Converting between the two, unpivoting, is a small query with real consequences for performance and for how the schema evolves. Interviewers ask this to see whether we know an efficient PostgreSQL technique, can compare it with the portable one, and think about the data model rather than only the query. In this answer, we will see the before and after, write the unpivot with LATERAL and VALUES, compare it with UNION ALL and other engines' options, handle NULLs and types, and then make the storage decision.

1The Data Before and After

The legacy table has one row per day with three metric columns. The charting service wants three rows per day, one per metric.

Unpivoting one wide row into three long rows
daymetricvalue
2025-06-01cpu41.5
2025-06-01mem67.2
2025-06-01disk12.9
From one source row: metrics(day = 2025-06-01, cpu_avg = 41.5, mem_avg = 67.2, disk_avg = 12.9).

2Unpivot With LATERAL and VALUES

A VALUES list is a small inline table written in the query. Inside a LATERAL subquery, it can refer to the columns of the current metrics row, because LATERAL lets a FROM item use columns of the items before it. So for each row of metrics, the VALUES list builds three rows from that row's own columns.

Java
SELECT m.day, v.metric, v.value
FROM metrics m
CROSS JOIN LATERAL (
VALUES ('cpu', m.cpu_avg),
('mem', m.mem_avg),
('disk', m.disk_avg)
) AS v(metric, value)
ORDER BY m.day, v.metric;
-- 2025-06-01 | cpu | 41.5
-- 2025-06-01 | disk | 12.9
-- 2025-06-01 | mem | 67.2
-- EXPLAIN:
-- Nested Loop
-- -> Seq Scan on metrics m
-- -> Values Scan on "*VALUES*" (3 rows per outer row, no table access)

The plan shows why this is efficient. The metrics table is read once, sequentially, and the Values Scan for each row only builds three tuples from values already in memory; it touches no table pages. For a table of 10 million days the cost is one scan plus 30 million cheap tuple constructions. Filters on day apply to the scan as usual, so WHERE m.day >= '2025-01-01' can use an index on day.

3The Portable Way: UNION ALL

Without LATERAL, the classic approach is three SELECTs glued together with UNION ALL, each producing one metric.

Java
SELECT day, 'cpu' AS metric, cpu_avg AS value FROM metrics
UNION ALL
SELECT day, 'mem' AS metric, mem_avg AS value FROM metrics
UNION ALL
SELECT day, 'disk' AS metric, disk_avg AS value FROM metrics;
-- EXPLAIN:
-- Append
-- -> Seq Scan on metrics
-- -> Seq Scan on metrics metrics_1
-- -> Seq Scan on metrics metrics_2

It runs everywhere and is easy to read, but notice the plan: three scans of the same table. For a small table that does not matter. For a large one, it triples the I/O, and each branch must repeat any WHERE filter, which is easy to forget in one of them. Planners generally do not merge the three scans into one, so the LATERAL form is the better choice whenever it is available. UNION ALL rather than UNION is important: UNION would try to remove duplicates, adding a sort or hash over all the output rows for no reason.

4Other Engines

Oracle and SQL Server have an UNPIVOT clause that expresses the operation directly, for example in SQL Server: SELECT day, metric, value FROM metrics UNPIVOT (value FOR metric IN (cpu_avg, mem_avg, disk_avg)) u. The metric names come out as the column names, cpu_avg and so on, which we may rename with a CASE. Note that UNPIVOT drops rows where the value is NULL, by default in Oracle (unless INCLUDE NULLS is given) and always in SQL Server, which is a behavioural difference from the VALUES approach.

MySQL has no UNPIVOT. UNION ALL works on every version. MySQL 8.0.14 and later support LATERAL derived tables, so a lateral subquery of SELECT ... UNION ALL SELECT ... over the outer row's columns reads the table once; check your version. Another trick builds a JSON array from the row and expands it with JSON_TABLE.

SQL
-- MySQL 8: one scan, using JSON_TABLE
SELECT m.day, j.metric, j.value
FROM metrics m,
JSON_TABLE(
JSON_ARRAY(JSON_OBJECT('metric', 'cpu', 'value', m.cpu_avg),
JSON_OBJECT('metric', 'mem', 'value', m.mem_avg),
JSON_OBJECT('metric', 'disk', 'value', m.disk_avg)),
'$[*]' COLUMNS (metric VARCHAR(10) PATH '$.metric',
value DOUBLE PATH '$.value')) AS j;

It works, but building and parsing JSON for every row costs CPU, so I would reach for the lateral form on MySQL versions that have it and keep JSON_TABLE as a fallback.

5NULLs and Types

Two details matter in the unpivoted output. First, NULLs: if mem_avg was not recorded on some day, the VALUES approach still produces a row with value NULL. A chart may prefer a gap to a NULL point, so we add WHERE v.value IS NOT NULL if the consumer expects only real values. Second, types: all values end up in one column, so they must share a type. If cpu_avg is numeric(5,2) and disk_avg is double precision, PostgreSQL resolves VALUES to a common type, but mixing, say, an integer count with a text status fails, and we cast explicitly, for example m.disk_avg::numeric.

6Choosing the Source of Truth

The query solves the charting service's need, but the question invites a design decision. One option keeps the wide table as the source of truth and exposes the long shape through a view, CREATE VIEW metrics_long AS (the LATERAL query). Nothing upstream changes, the charting service queries the view, and filters on day still push down into the base table. This is right when the set of metrics is stable and other consumers rely on the wide layout.

The other option migrates storage to the long format: metric_values(day, metric, value) with a primary key on (metric, day). Adding a new metric, say net_avg, becomes inserting rows instead of an ALTER TABLE and a code change in every consumer. The costs are three times as many rows, each carrying PostgreSQL's per-row overhead of about 24 bytes for the tuple header, plus index entries, so storage can grow several times for narrow numeric data, and queries that need all metrics for one day must read several rows or pivot back. Time-series databases and TimescaleDB handle the long format well with compression.

My usual choice is the view first, because it delivers the feature without a migration, and a move to long storage only when the number of metrics starts changing often. The decision is easy to revisit because the view already defines the long shape the consumers depend on.

Wide table with a view versus long storage
ConcernKeep wide table plus viewMove to long storage
Adding a metricALTER TABLE and view changeInsert rows, no schema change
StorageOne row per dayOne row per day per metric, more overhead
Read all metrics for a dayOne rowSeveral rows, or pivot back
Migration effortNoneBackfill and change writers
Best whenMetrics are few and stableMetrics change often

7Follow-up questions

Can the unpivot be reversed for consumers that still want wide data?

Yes, with conditional aggregation: SELECT day, MAX(value) FILTER (WHERE metric = 'cpu') AS cpu_avg, ... FROM metric_values GROUP BY day. If storage moves to long format, a view like this keeps old wide consumers working during the transition.

Would you include units or metadata in the long format?

I would keep metric metadata, such as unit, display name and aggregation rule, in a separate metrics catalogue table keyed by metric name, rather than repeating it on every row. The charting service joins to it or caches it, and adding a metric means adding one catalogue row.

How does this interact with indexing for the charting queries?

Charting queries usually ask for one or a few metrics over a time range, so in long storage the primary key (metric, day) serves them with a range scan. With the view over the wide table, an index on day serves the range, and the lateral expansion happens only for the selected days.

8Conclusion

In this answer, we unpivoted a wide metrics table into (day, metric, value) rows. In PostgreSQL, CROSS JOIN LATERAL with a VALUES list reads the table once and emits three rows per input row, while a UNION ALL of three SELECTs is portable but scans the table three times. Oracle and SQL Server offer UNPIVOT, with different NULL handling, and MySQL uses UNION ALL, a lateral derived table on recent versions, or JSON_TABLE. We also handled NULLs and types, and weighed keeping the wide table behind a view against moving storage to the long format, which lets metrics be added without schema changes.

What to say in the interviewAbout 90 seconds aloud

Open with

In PostgreSQL I'd use a lateral VALUES list: SELECT m.day, v.metric, v.value FROM metrics m CROSS JOIN LATERAL (VALUES ('cpu', m.cpu_avg), ('mem', m.mem_avg), ('disk', m.disk_avg)) AS v(metric, value).

Then, if they want more

Because the VALUES list can reference the current row's columns, the table is scanned once and each row just produces three tuples in memory; the plan is a nested loop over a seq scan and a cheap values scan.

The portable alternative is a UNION ALL of three SELECTs, one per metric, which works everywhere but scans the table three times and repeats any filter in each branch, and it must be UNION ALL, not UNION, to avoid a pointless deduplication.

Oracle and SQL Server have an UNPIVOT clause, which drops NULL values by default, and in MySQL I'd use UNION ALL, a lateral derived table on 8.0.14 or later, or a JSON_TABLE trick. I'd also decide about NULLs and make sure the value columns share a type.

Then the bigger question is the model: for now I'd keep the wide table as the source of truth and expose the long shape as a view, and if metrics start being added often, I'd migrate storage to a long table keyed by metric and day, so a new metric is new rows rather than a schema change.

About this answer

Last updated
12 November 2026
Versions it names
MySQL 8, MySQL 8.0
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 "A legacy table metrics(day, cpu_avg, mem_avg, disk_avg) must be turned into rows (day...": https://scrivio-interview-library.netlify.app/databases/advanced-sql/af6dfc0b5a/