Query
A query is a request to a database for specific data. It states which fields, rows and conditions are wanted, and the database returns a result set. In relational databases, queries are written in SQL.
What it is
A query is a precise request to a database for the data that answers a question. It names the fields to return, the table or tables to read and the conditions that rows must meet. The database returns a result set, which is a table of the rows and columns requested.
A query has the following parts:
- Selection of fields, the columns to return.
- A source, the table or tables to read.
- Conditions, which filter rows by value or date.
- Grouping and summary functions, which count, sum or average rows.
- Ordering, which sets the sequence of the result.
In a relational database, queries are written in SQL. The NIST MOSAIC guide describes the SELECT statement as the command that pulls data from a database, with a WHERE clause to limit the rows returned and ORDER BY to sort them. NIST also shows counting queries, which count the rows that meet stated conditions, optionally by group. SELECT is the SQL operation that reads data. The other basic operations insert, update and delete data.
A query that only reads leaves the stored data unchanged.
Why it matters
A query turns a business question into a repeatable extraction. The same query run on the same data returns the same result, so a figure can be traced and rerun.
A condition that is too narrow drops rows and understates a total. One that is too wide includes rows that should be excluded.
Worked example
Illustrative numbers. A table holds 1,000 invoice rows. The question is the total invoiced to one customer in one quarter.
The query selects the amount column, restricts rows to that customer and to dates in the quarter, and sums the amounts. Suppose 40 rows match and sum to 120,000 euro.
The analyst compares the result with the ledger total for that customer. A difference points to a missing condition or to a row that the filter removed.
Who uses it
- Data analysts write queries to extract and shape data for analysis.
- Business intelligence analysts build reports on saved queries.
- Regulatory reporting analysts query source data to populate filings and trace figures.
- FP&A analysts extract actuals from reporting databases for models and variance reports.
Common confusions
- A query is a request; the result set is the answer. A query does not store its result unless it is saved as a table.
- A query is not the same as SQL. SQL is one language in which queries are written.
- A query that runs without error is not necessarily correct. The result must still be checked against a control total or the ledger.
- Reading data and changing data are different operations. A read query does not alter records.