Highest and Lowest Cloud Costs

A medium SQL interview practice problem on DataDriven. Write the query and run it against a real database, with instant feedback.

Domain
SQL
Difficulty
medium
Seniority
L3
Asked in
Siemens

Problem

Which line items in cloud_costs sit at the very top and the very bottom of the whole bill, counting every entry whose amount hits either extreme? A billing analyst wants each one with its cost ID, amount and service name, plus a cost_type reading 'Highest Cost' or 'Lowest Cost'.

The extremes in cloud spending.

Tables

cloud_costs

Columns: cost_id INTEGER, provider TEXT, svc_name TEXT, region TEXT, amount REAL, acct_id TEXT, bill_date TEXT

cloud_costs: 10 of 200 rows
cost_idprovidersvc_nameregionamountacct_idbill_date
543GCPS3us-west-219.33acct-10012026-02-01
586AzureRDSeu-west-137.16acct-10022026-03-01
629awsLambdaap-southeast-154.99acct-10032026-04-01
672gcpBigQueryus-central172.82acct-10042026-05-01
715AWSCloud Runeurope-west190.65acct-10052026-06-01
758GCPBlob Storageus-east-1108.48acct-10062026-07-01
801AzureCosmos DBus-west-2126.31acct-10072026-08-01
844awsCloudFronteu-west-1144.14acct-10082026-09-01
887gcpPub/Subap-southeast-1161.97NULL2026-01-01
930AWSEC2us-central1179.8acct-10102026-02-01

Expected output

First 4 of 4 rows
cost_idamountsvc_namecost_type
48001784.5EC2Highest Cost
100049001784.5EC2Highest Cost
4585-268.5Cloud RunLowest Cost
10004895-268.5Cloud RunLowest Cost

Worked solution and explanation

Why this problem exists in real interviews

Cloud cost anomaly reports always need both extremes side by side: the runaway charge and the suspiciously cheap line item. Interviewers use this prompt to see whether you can label two halves of a result set, preserve ties at each extreme, and stitch them together without losing either rows or column alignment.


Break down the requirements

Step 1: Find every row tied at MAX(amount)

Use a scalar subquery WHERE amount = (SELECT MAX(amount) FROM cloud_costs). This returns every row at the max, so a single huge invoice and any duplicates all come back.

Step 2: Find every row tied at MIN(amount), then label both halves

Mirror the same pattern for MIN. Each half projects a literal label, 'Highest Cost' or 'Lowest Cost', as cost_type so the consumer can distinguish them after the union.

Step 3: Glue with UNION ALL, not UNION

UNION ALL preserves duplicates and skips the implicit DISTINCT sort. The two halves cannot collide because the cost_type literals differ, so UNION ALL is both correct and cheaper.


The solution

Two filtered selects unioned with literal labels
SELECT cost_id, amount, svc_name, 'Highest Cost' AS cost_type
FROM cloud_costs
WHERE amount = (SELECT MAX(amount) FROM cloud_costs)
UNION ALL
SELECT cost_id, amount, svc_name, 'Lowest Cost' AS cost_type
FROM cloud_costs
WHERE amount = (SELECT MIN(amount) FROM cloud_costs)

Common follow-up questions