Which SQL commands does a controller really need?
By Daniel Stoffels
Short answer
Ten SQL building blocks are particularly useful for recurring finance analyses: SELECT, WHERE, GROUP BY with sums, JOIN, ORDER BY, HAVING, CASE, DISTINCT, date filters and WITH or subqueries. With read-only access, these can select, join, aggregate and check data, provided row meaning, signs and business scope are clear.
Key points
- SQL is a language for querying and modifying relational databases; the focus for controllers here is exclusively on reading.
- Each result row needs a clear meaning, such as a posting, invoice line or cost centre total.
- JOIN can multiply amounts if one source row finds several matching rows on the other side.
- Filters, signs, currency and data cut-off determine what a total contains.
- A saved query with control totals is easier to trace than repeated manual copying and combining.
Record the scope in writing
Purpose, entity, period, currency and views used
Check every processing step
Row counts, missing mappings and amounts
Retain the query and result version
Query with parameters and data cut-off
Definition
SQL stands for Structured Query Language and is a language for relational databases, whose information is held in linked tables. A read-only SQL query describes which data to select, how to join tables and how to calculate or order results.
Understand the data before the first command
First clarify what a row represents. An invoice header may contain the total amount, while an invoice line contains the amount for a single item. If both levels are joined and summed without checking, the query counts the total amount several times. SQL can answer a substantively incorrect question without any technical error.
The following expressions use a simplified read-only view named buchungen. A view provides approved data like a table. Each row here represents a posting line with posting identifier, posting date, status, account, cost centre, cost type and amount. The view is already restricted to a defined entity, euros as the currency and the expense accounts needed. For the cost view shown, expenses are defined as positive and their offsetting entries as negative. Field names and syntax must be adapted to the actual data model.
Have read-only access to the required data set up. Even a query can place demands on very large datasets. Start with defined periods and approved views; coordinate extensive analyses with technical support. Write protection and appropriate access are enforced through permissions, not through a statement of intent in the query text.
SELECT: choose the fields needed
SELECT determines the output columns; FROM determines the data source. The expression SELECT buchungsdatum, konto, kostenstelle, betrag FROM buchungen shows the fields for an initial account check. Select the required columns deliberately. This makes understanding easier and avoids carrying unnecessary detail into every analysis.
A column heading can be given a clearer name using AS. Renaming does not change its business meaning, however. A field named betrag does not become net revenue simply because the output receives that name. Check the source definition before deriving a measure from it.
WHERE: restrict individual records
WHERE filters rows before aggregation. SELECT konto, betrag FROM buchungen WHERE status = 'gebucht' selects only rows with this confirmed status. Further conditions can be linked with AND. OR is used for alternative conditions; parentheses make their grouping clear.
Check how missing values are handled. NULL in SQL denotes a missing or unknown value. WHERE kostenstelle IS NULL searches for it; comparison with an empty string does not automatically find the same thing. A missing cost centre differs in substance from an explicitly assigned general area.
GROUP BY and SUM: aggregate costs
GROUP BY combines rows with identical attributes. SELECT kostenstelle, kostenart, SUM(betrag) AS aufwand FROM buchungen GROUP BY kostenstelle, kostenart produces a total for each combination. SUM is an aggregate function, a calculation across several rows. This creates the basis for a cost centre analysis.
The grouping determines the meaning of the result row. Adding another dimension, such as month, creates correspondingly finer groups. SUM does not treat missing amounts as confirmed zeros. Check such gaps separately. Different currencies do not belong in the same monetary total without a validated conversion.
JOIN: connect postings and master data
JOIN connects tables through matching keys. SELECT b.konto, k.name, b.betrag FROM buchungen b LEFT JOIN kostenstellen k ON b.kostenstelle = k.kennung adds the name from the cost centre table. The abbreviations b and k are table aliases and shorten unambiguous field references. LEFT JOIN also retains postings without a matching master record; its added fields then remain empty in the sense of NULL.
INNER JOIN would retain only rows with a match on both sides. This can hide missing mappings unnoticed. Also check whether the identifier in kostenstellen really is unique. If a posting finds several master records, the row count grows and its amount is output several times. Compare counts and amounts before and after the join.
ORDER BY: sort results meaningfully
ORDER BY sets the sequence. ORDER BY aufwand DESC sorts an aggregated cost view in descending order; ASC means ascending. Large items become visible first. Without explicit sorting, a query should not be assumed to retain the same order over time.
For reproducible lists, add a further unambiguous sort for equal amounts, such as cost centre and cost type. Sorting changes no total and explains no variance. It helps select the items to be examined subsequently from a business perspective.
HAVING: select groups by their total
HAVING filters after aggregation. SELECT kostenstelle, SUM(betrag) AS aufwand FROM buchungen GROUP BY kostenstelle HAVING SUM(betrag) > 0 shows cost centres with a positive overall total. WHERE, by contrast, would test individual source rows. This distinction is essential when offsetting entries reduce the net total.
For an exception list, the threshold can be supplied as an approved parameter. Document the unit and purpose. An investigation threshold is neither a posting rule nor evidence of an error. Show the underlying items when questions arise.
CASE: express analysis rules visibly
CASE produces conditional results. CASE WHEN betrag IS NULL THEN 'Amount missing' WHEN betrag < 0 THEN 'Negative amount' ELSE 'Non-negative amount' END labels the cost view defined here by data gap and sign. Business account mappings can also be rule-based. For extensive mappings, a maintained mapping table is easier to review jointly.
Remember the fallback case. The rule shown checks missing amounts first so that they are not given an apparently valid sign category. A negative number alone also does not prove a credit note: its meaning depends on the business transaction and the source's sign convention.
DISTINCT: display different values
SELECT DISTINCT kostenstelle FROM buchungen shows the different cost centre values in the selected data. This helps investigate new, unexpected or missing mappings. DISTINCT removes identical combinations of the selected output fields, not automatically duplicate business transactions.
Do not therefore use DISTINCT to repair an incorrect JOIN. Two legitimate postings may be identical in the visible fields and would then collapse into one. Investigating duplicates requires a defined transaction identifier and an explanation of why the same identifier occurs several times.
Date filters: define complete periods
A clearly traceable period uses an inclusive lower bound and an exclusive upper bound: buchungsdatum >= :von AND buchungsdatum < :bis. The colon notation here represents parameters to be supplied. Their actual syntax depends on the query tool used. For a month, :bis is the beginning of the following month.
This approach avoids inadvertently including the last day only up to midnight for fields containing a time. Also check whether posting date, document date or the period of service is intended. A technically complete date filter can select the wrong period from a business perspective. For timestamps, the convention governing their time reference must also be clarified.
WITH: divide a query into readable parts
WITH names an intermediate result within a query. WITH basis AS (SELECT kostenstelle, kostenart, betrag FROM buchungen WHERE status = 'gebucht') SELECT kostenstelle, SUM(betrag) FROM basis GROUP BY kostenstelle separates selection from aggregation. A subquery can fulfil a similar task within a larger query.
Naming helps check the business steps. Examine the rows in basis first, then the totals. WITH structures the query text; execution speed and storage must be considered separately. A retained report version and its approval need their own rule.
Turn a query into a reliable analysis
Record the scope in writing
Document purpose, entity, period, currency and views used. Check row meaning and add a suitable transaction identifier for later queries.
Check every processing step
Compare row counts, missing mappings and amounts before and after joins. Investigate unusual changes before adding further calculations.
Retain the query and result version
Retain the query used with parameters and data cut-off traceably. A later rerun can produce different values because of late postings. Document changes approved by the relevant business owner.
Reconcile an aggregated cost view
The round amounts are illustrative and stated in thousands of euros, abbreviated €k. Entity, currency and expense accounts are already restricted by the read-only view. Status and period are selected using the following conditions. The query returns the four detail rows; for the table, amounts are then displayed in €k. The total row is an additional control calculation and is not part of the query output.
The complete query is: SELECT kostenstelle, kostenart, SUM(betrag) AS aufwand FROM buchungen WHERE status = 'gebucht' AND buchungsdatum >= :von AND buchungsdatum < :bis GROUP BY kostenstelle, kostenart ORDER BY kostenstelle, kostenart; The parameters :von and :bis define the reporting period as described above.
For production, the calculation is 100 + 50 = 150; for administration, 20 + 30 = 50. By cost type, the totals are 120 for materials and 80 for maintenance. Both routes lead to total expenses of 200. This control total must match the posting dataset with the same scope. A match does not replace checking whether each item has been assigned to the correct cost centre.
| Cost centre | Cost type | Expense |
|---|---|---|
| Production | Materials | 100 |
| Production | Maintenance | 50 |
| Administration | Materials | 20 |
| Administration | Maintenance | 30 |
| Control total | All cost types listed | 200 |
Common errors in finance queries
Verification: another person can follow the query with the documented parameters, explain its row meaning and reconcile the total against the same business scope. Joins change amounts only where this is intended and demonstrated.
- Using signs without checking: clarify how expenses, revenue and corrections are represented in the source.
- Concealing duplicate totals with DISTINCT: check the keys and relationships between tables.
- Filtering out missing mappings: keep unassigned items visible and assign their investigation.
- Looking only at the final result: compare appropriate control totals and investigate individual transactions.
Frequently asked questions
Does a controller need to be able to administer databases?
Understanding the approved data and queries is sufficient for the analyses described. Setup, permissions and technical support need their own responsibilities. The business definition and control calculation remain part of the analysis.
Does SQL replace spreadsheets?
SQL can prepare recurring selection and aggregation transparently. A spreadsheet remains usable for analysis and presentation. Keep the source and calculation traceable there too, and separate manual additions from imported data.
Can AI write the query?
A draft can help with formulation. Check the data model, rights, joins and result from both business and technical perspectives. Plausible syntax does not prove a correct measure; enter only information whose use for this purpose is permitted.
Why can a query be wrong despite a correct total?
Errors can offset one another. Incorrect mappings, missing and duplicate transactions may remain invisible in the overall total. Check subgroups, identifiers and individual business transactions as well.
Can the expressions shown be executed directly?
They explain the building blocks using a simplified schema. Actual field names, data types, parameters and some syntax depend on the database and tool. Coordinate adaptation with technical support and use the designated read-only access.
Sources
Last updated:
General knowledge of SQL building blocks and business validation of finance analyses
Summary by Heldensystem