Before You Build the Query, Decide What Counts as an Answer
Hatched by Kai Nguyen
Aug 19, 2026
10 min read
2 views
92%
What if many software mistakes begin before the code is written, at the moment we quietly accept a vague question as if it were a precise one?
A developer is asked to show the most popular books published recently. They reach for a familiar pattern: fetch the records, sort them, perhaps remove duplicates, and display the result. The code may run perfectly. The database may return exactly what it was instructed to return. Yet the result can still be wrong, because nobody decided what "popular," "recent," or even "book" means.
This is the overlooked connection between first principles thinking and data retrieval: a query is not merely an instruction to a database. It is a formal statement about what you believe an answer is. SQL makes that statement visible through filtering, ordering, and selection. First principles thinking provides the discipline to ask whether the statement corresponds to the real problem.
The deepest skill is therefore not knowing more patterns or more syntax. It is learning to move deliberately between two activities: reducing a problem to fundamental truths, then reassembling those truths into a useful view.
Before asking how to retrieve an answer, ask which distinctions make the answer meaningful.
The Hidden Assumptions Inside Every Query
A database table looks concrete. It contains rows and columns, so it feels like reality itself. But a table is already an interpretation of reality. Someone decided which entities mattered, which properties deserved columns, how relationships should be represented, and what could be left out.
The same is true of an application. A request such as "show users who are active" appears simple until we inspect its assumptions. Does active mean logged in during the past day, opened an email this week, or made a purchase this month? Is a user active if an automated process acts on their behalf? Which time zone applies? What happens when activity data is missing?
In SQL, the WHERE clause exposes this hidden work. It accepts an expression that evaluates to true or false. That sounds technical, but it is also philosophical: the system must turn a fuzzy category into a testable proposition. Each row either satisfies the condition or it does not.
Suppose we write:
SELECT *
FROM users
WHERE last_login >= '2026-08-01';
This query is not simply "finding active users." It defines active users as people whose recorded last login falls on or after a particular date. That may be an excellent operational definition, or it may be a misleading substitute for the real goal. The syntax cannot decide.
This is why spending time understanding the domain is not a delay before the real engineering begins. It is the real engineering. Code only becomes straightforward after the problem has been made precise enough to survive contact with implementation.
A useful diagnostic is to separate three layers:
- The user need: What decision or action should this result support?
- The domain truth: What facts exist independently of the software interface?
- The operational test: What condition can the system actually evaluate?
Confusion occurs when these layers are collapsed. A product manager expresses a need, a developer translates it into a field, and the field quietly becomes treated as truth. First principles thinking interrupts that slide by asking what the system is genuinely trying to know.
The Database as a Laboratory for First Principles
A well formed query performs several distinct intellectual operations. Keeping them separate creates a practical framework for reasoning about software problems.
1. Filter: What qualifies?
WHERE is the act of separating relevant cases from irrelevant ones. It forces a boundary. That boundary should be justified by the purpose of the query, not by whichever column happens to be available.
Imagine an online library trying to identify books for a recommendation page. A careless filter might use:
WHERE publication_year >= 2020
But the page might actually need books added to the catalogue recently, not books published recently. Those are different facts. A translated novel published in 1950 and added this year may be highly relevant, while a 2021 title added five years ago may not be.
The first principles question is: which fact explains the decision we are trying to make? The field name is not the answer. It is evidence that may or may not represent the answer.
2. Project: What information is essential?
Although basic retrieval examples often use SELECT *, real systems should be suspicious of the star. Selecting every column confuses availability with necessity. It increases coupling, exposes data that may not belong in the result, and makes it harder to see what the query actually claims to know.
If a screen needs a title and publication year, then selecting those fields makes the shape of the answer explicit:
SELECT title, publication_year
FROM books
WHERE genre = 'history';
This resembles decomposition in problem solving. Instead of treating the whole system as an undifferentiated object, we identify the minimum components required for the task. The goal is not always minimal code or minimal data. The goal is minimum sufficient structure.
That phrase matters. A result can be too broad to be useful, but it can also be too narrow to support the decision. First principles does not mean stripping everything away indiscriminately. It means understanding what each element is doing.
3. Distinguish: Which repetitions matter?
DISTINCT is often presented as a small convenience for retrieving unique values. Conceptually, it raises a larger question: when two records look identical for our purpose, should they count as one thing or two?
For example:
SELECT DISTINCT genre
FROM books;
This does not tell us that the underlying books are duplicates. It tells us that, for this particular question, multiple books sharing a genre should collapse into one visible category.
That distinction is crucial in application design. A customer can have multiple orders, a product can have multiple reviews, and an author can have multiple books. Whether repeated appearances represent meaningful multiplicity or distracting repetition depends on the task.
A dashboard showing all transactions should preserve repetitions. A filter showing available genres should remove them. The data has not changed. The level of abstraction has changed.
4. Order: What should be seen first?
Rows in a table are not necessarily ordered. This is more than an implementation detail. It is a warning against assuming that storage order carries meaning.
If a result must be arranged, the query must say so:
SELECT title, publication_year
FROM books
ORDER BY publication_year DESC;
The explicit DESC expresses a priority: newer items should appear first. Without ORDER BY, any apparent order is accidental or dependent on internal behavior. Treating an accident as a guarantee is one of the most common ways systems become fragile.
The same mistake occurs in larger reasoning. Teams often inherit an order of operations from an old workflow, a familiar design pattern, or the sequence in which data happens to arrive. But sequence should be justified by purpose. What deserves attention first? What is the user trying to optimize? What constraint has priority?
Sorting is therefore a form of judgment. It converts a collection into a hierarchy.
From Design Patterns to Query Patterns
Design patterns are useful because they package solutions to recurring classes of problems. But a pattern applied before the problem is understood can become camouflage. It gives a vague requirement the appearance of rigor.
The same danger exists in SQL. Developers can write technically sophisticated queries that answer the wrong question with impressive efficiency. They may add joins, nested subqueries, indexes, and abstractions while never clarifying the intended meaning of the result.
A stronger process begins with decomposition. Consider the request: "Give me the best books to recommend to each user."
That sentence contains several separate problems:
- Which users are eligible?
- What does "best" mean: popularity, quality, novelty, or relevance?
- Are recommendations based on individual history or general trends?
- Should books already read be excluded?
- How many results should appear?
- Does the ranking need to be stable when two books have equal scores?
Only after these questions are answered can the query become an honest representation of the product decision. The architecture may then be simple. Perhaps the system needs a filter for eligibility, a score for relevance, an ordering rule, and a limit. Or perhaps the problem is not a database retrieval problem at all, but a measurement problem requiring better data.
This suggests a practical rule:
If choosing a design pattern feels difficult, the problem may still be underspecified. If the problem is genuinely understood, the pattern usually becomes an implementation detail.
The same rule applies to query construction. When a query keeps growing through patches, ask whether it is expressing one coherent definition or compensating for an unclear one.
A Four Stage Method for Better Technical Decisions
The ideas above can become a repeatable workflow for coding, analytics, and product design.
Stage one: State the decision
Do not begin with "What data do we have?" Begin with "What decision will this result enable?" A report, endpoint, or screen exists for a reason. Naming the decision prevents the available schema from dictating the question.
For example, a hiring dashboard may be intended to identify candidates needing follow up. That is different from listing candidates with the most recent application activity. The latter may be easy to query, but ease is not relevance.
Stage two: Identify irreducible facts
List the facts that must be true for the result to be useful. These are your working first principles. They might include:
- A candidate must have an open application.
- A follow up is needed only after a defined number of days.
- The responsible recruiter must be identifiable.
- Activity from automated systems should not reset the clock.
These statements are more valuable than prematurely selecting a framework or writing a complex query. They provide criteria against which implementation choices can be tested.
Stage three: Translate facts into explicit operations
Now map each principle to an operation. Filtering determines eligibility. Selection determines the information required. Deduplication determines the unit of analysis. Ordering determines priority.
If the result needs one row per candidate, but the database contains many activity records per candidate, the query must address that mismatch directly. Otherwise, the system may display the same candidate repeatedly and make the workload appear larger than it is.
This translation is where domain reasoning becomes software. It is also where ambiguities become visible. If a principle cannot be translated into a reliable test, the problem may require a new field, a better event model, or a decision from the product owner.
Stage four: Reassemble and challenge the result
After the pieces are defined, combine them into the simplest coherent solution. Then challenge it with counterexamples.
Ask what happens when a value is missing, two records tie, a row appears twice, the date crosses a time zone, or the storage engine returns rows in a different order. Ask whether the result remains meaningful when the data grows.
This final step matters because decomposition can create a false sense of certainty. A problem may be divided into correct local operations whose combination is still wrong. Reassembly is not just putting parts back together. It is testing whether the parts preserve the original purpose.
Key Takeaways
- Treat every query as a definition. A
WHEREcondition does not merely retrieve data. It declares what qualifies as relevant. - Separate need, truth, and test. Clarify the user decision, identify the domain fact behind it, and only then choose the field or Boolean expression that approximates it.
- Make priority explicit. If order matters, use
ORDER BY; if priority in the project matters, name it. Accidental order is not a strategy. - Choose the right unit of analysis. Use distinctness, grouping, or restructuring when the visible answer should represent categories, entities, or events rather than raw rows.
- Challenge the assembled result. Test missing values, duplicates, ties, changing data, and boundary conditions before trusting a technically valid output.
The most mature developers are not those who can produce the most elaborate solutions. They are the ones who notice when a system is answering a different question from the one people think they asked.
A database table is a collection of possibilities. A query turns those possibilities into a view. A design turns that view into an action. At every step, choices about relevance, identity, order, and priority are being made, whether or not anyone names them.
So the next time you open an editor, resist the reflex to search for a pattern or compose a query. First ask: What must be true for this answer to deserve the name answer? Once that question is clear, the code often stops feeling like invention. It becomes what good code has always been: a precise reconstruction of a problem already understood.
Sources
Hatch New Ideas with Glasp AI 🐣
Glasp AI allows you to hatch new ideas based on your curated content. Let's curate and create with Glasp AI :)
Start Hatching 🐣