Total Cost by Category

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

Domain
SQL
Difficulty
easy
Seniority
L3
Asked in
Siemens

Problem

Every allocation in cost_allocs counts, across all of its periods, and the negative amounts are credits that net against spend rather than being dropped. Give the FinOps team's budget review the total amount per cost category.

Total spend per category.

Tables

cost_allocs

Columns: alloc_id INTEGER, team_name TEXT, svc_name TEXT, region TEXT, amount REAL, period TEXT, acct_id TEXT, category TEXT

cost_allocs: 10 of 200 rows
alloc_idteam_namesvc_nameregionamountperiodacct_idcategory
129data-engS3us-west-283.212026-02acct-101storage
158ml-teamRDSeu-west-1156.422026-03acct-102network
187frontendLambdaap-south-1229.632026-04acct-103database
216backendBigQueryus-central1-120.52026-05acct-104ml
245devopsCloudFronteurope-west1376.052026-06acct-105other
274securityEKSap-southeast-1449.262026-07acct-106compute
303mobileSQSeu-central-1522.472026-08acct-107storage
332PlatformEC2us-east-1595.682026-09NULLnetwork
361DATA-ENGS3us-west-2668.892026-01acct-109database
390platformRDSeu-west-1742.12026-02acct-110ml

Expected output

First 5 of 6 rows
categorytotal_amount
compute281867.52
database290135.47
ml274132.65
network287382.82
other269813.3

Worked solution and explanation

Strip off the FinOps wording and this is a one-key rollup of a ledger: six cost categories, one total each, every row landing in exactly one bucket. Nobody fails it for lack of syntax. People fail it by answering a different question. One version is a grand total over cost_allocs that never mentions category. The other is a bare category next to SUM(amount) with nothing bucketing by it, which a permissive engine runs happily, returning one row: the whole table's spend glued to whichever category it read first. The second is the dangerous one, because nothing errors and the review books every dollar to one bucket.

Getting to the query

Step 1: Read the grain off the output

The answer has one row per category, so category is the key every row is bucketed by. The seed holds six values ('compute', 'storage', 'network', 'database', 'ml', 'other') across 200 rows, and the preview already shows that one-row-per-category shape. Read the grain from the shape before writing a clause.

Step 2: Total amount inside each bucket, signs and all

SUM(amount) per group, aliased total_amount so the column says what it holds. Every row keeps its sign: alloc_id 216 is a credit of -120.5 booked to 'ml', and it nets against that category's spend instead of being filtered away. No period filter either: the review covers every period in the table.

One total per category
SELECT category, SUM(amount) AS total_amount
FROM cost_allocs
GROUP BY category

Common follow-up questions