The Hidden Cost of Making SQL Human Friendly

Kai Nguyen

Hatched by Kai Nguyen

Jun 16, 2026

8 min read

91%

0

The Problem Is Not Speed, It Is Shape

Most people think query optimization is about making SQL run faster. That is only half true. The deeper issue is that a query can be written in a way that is easy for humans to read, but hard for the database to reason about. In other words, the real question is not, "How do I ask for the right rows?" It is, "How do I ask for them in a form the engine can answer cheaply?"

That distinction changes everything. A database does not experience your query as a neat sentence. It experiences a sequence of expressions, comparisons, filters, calculations, and transformations over rows. If those expressions are shaped well, the engine can use indexes, stop early, avoid sorting, and skip unnecessary work. If they are shaped poorly, it may still return the right answer, but only after grinding through far more data than needed.

This is why SQL optimization is not just a technical tuning exercise. It is a lesson in translating intent into machine friendly structure. The best queries are not merely correct. They are legible to the optimizer.


SQL Is a Language of Expressions, Not Just Clauses

At the surface, SQL looks like a set of keywords: SELECT, WHERE, GROUP BY, ORDER BY. But underneath, nearly everything is an expression, something that evaluates to a value. A column reference is an expression. A comparison like price > 100 is an expression. A function call is an expression. Even a string concatenation with || is an expression.

That matters because the database does not just read clauses in the order we type them. It evaluates expressions row by row according to its execution logic. A WHERE clause that looks simple to us can become expensive if it wraps an indexed column in arithmetic, negation, or a function. When that happens, the database often loses the ability to use the index efficiently, because the value in the column is no longer directly searchable.

Think of an index as a library catalog. If you ask for books by exact title, the catalog helps immediately. If you ask, "Show me books whose title, after being reversed, contains this pattern," the catalog is suddenly much less useful. The engine can still answer, but it may have to inspect many more rows.

This is where SARGable comes in, meaning searched argument able. A SARGable predicate is one that can take advantage of an index. The phrase sounds technical, but the intuition is simple: the filter should be written so the engine can search, not merely compute.

A good SQL predicate does not just describe what you want. It preserves a path for the database to find it quickly.

This is why tiny syntactic choices matter. WHERE created_at >= '2025-01-01' is usually friendly to an index. WHERE DATE(created_at) = '2025-01-01' may be much less so, because the function hides the raw column behind a calculation. Likewise, WHERE status <> 'closed' can be less efficient than a positive match in some cases, because negation is harder to narrow down than inclusion.

The lesson is not that functions or arithmetic are bad. The lesson is that expressions have shape, and shape determines searchability.


The Real Tension: Human Clarity Versus Engine Clarity

Here is the deeper tension connecting all of this: the query that is clearest to write by hand is often not the query that is clearest to execute by machine. SQL invites us to think declaratively, to state what result we want. But the optimizer must convert that statement into a practical plan: which rows to scan, which index to use, when to filter, when to sort, when to group, and how much work can be skipped.

That creates a subtle design challenge. We want code that is expressive, maintainable, and understandable. But we also want code that respects the database's internal mechanics. The best SQL is a compromise between these two forms of clarity.

For example, wildcard searches show this tension vividly. A pattern like LIKE '%smith' is human friendly and semantically precise, but the leading wildcard often prevents index use. The database cannot jump to the end of the string the way it can jump to a prefix. By contrast, LIKE 'smith%' gives the engine a starting point and usually opens the door to faster lookup.

The same tension appears with sorting and grouping. We often treat ORDER BY and GROUP BY as innocent finishing touches, but they can be expensive if applied to huge intermediate sets. The database may need to collect, compare, and rearrange far more data than necessary. If a WHERE clause can reduce the candidate rows first, the later operations become dramatically cheaper.

This suggests a useful mental model: do not think of SQL as a list of instructions, think of it as a narrowing funnel. Each part of the query should reduce uncertainty as early and as cheaply as possible. The earlier the funnel narrows, the less work remains downstream.


Write Queries Like a Detective, Not a Journalist

A journalist often tells the story in the order it happened. A detective works backward from the evidence and asks, "What can I eliminate first?" Good query design is more like detective work.

Suppose you want the most recent 20 orders for active users in the northeast region. A naive version might join everything, compute some derived columns, sort the entire result, and then limit to 20. A better version asks first: what can be filtered at the source? Which columns are already indexed? Which predicates can be written directly on those columns? Can the WHERE clause remove most rows before the sort ever happens?

Consider a concrete example:

SELECT
  order_id AS id,
  created_at,
  total_amount || ' USD' AS formatted_total
FROM orders
WHERE created_at >= '2025-01-01'
  AND region = 'northeast'
ORDER BY created_at DESC
LIMIT 20;

This query is doing several things well. The comparisons are direct. The filters are early. The output is renamed with AS for clarity. The formatted display value is created at the end, not in a way that blocks filtering. If there is an index on created_at or a composite index on region, created_at, the engine has a much better chance of finding a cheap path.

Now compare that with a less cooperative version:

SELECT
  order_id,
  created_at,
  total_amount || ' USD'
FROM orders
WHERE DATE(created_at) = '2025-01-01'
  AND LOWER(region) = 'northeast'
ORDER BY created_at DESC;

This version may read nicely, but it places functions on the indexed columns inside the WHERE clause. The engine may have to compute those values row by row before it can even decide whether a row qualifies. The result may be identical, but the path is much more expensive.

This is why the question is not just, "Is the query logically correct?" It is also, "Can the database prune the search space before doing expensive work?" That is the essence of optimization.


The Best Optimization Is Often a Better Vocabulary

One of the most overlooked features in SQL is the humble AS keyword. Renaming columns may look cosmetic, but it is part of a larger discipline: making each expression's meaning explicit. A query with clear aliases, clean predicates, and direct comparisons is easier for humans to understand and easier for teams to maintain.

That clarity feeds performance indirectly. When a query is written in a disciplined, semantically transparent way, it is easier to see whether a column is being used in a search friendly manner. It is easier to spot accidental transformations, such as wrapping an indexed field in a function or hiding a filter inside a computed expression. It is easier to ask whether a predicate is inclusive or exclusive, whether a wildcard is prefix based or leading, and whether a limit can be applied sooner.

This is an underrated insight: query optimization is partly a vocabulary problem. If you cannot name what the engine needs, you may accidentally write against it. If you can name the difference between a searchable predicate and a post processing expression, you start seeing SQL differently.

A practical way to think about this is to divide query work into two kinds:

  1. Search work, which helps the engine find candidate rows quickly.
  2. Presentation work, which shapes the final answer for humans.

Search work belongs as early as possible, and presentation work belongs as late as possible. WHERE filters, indexes, and selective predicates are search work. AS aliases, concatenated labels, and final formatting are presentation work. Mixing them too early often makes the engine do the wrong kind of labor at the wrong time.

The fastest query is usually the one that delays human friendliness until after machine friendliness has done its job.

That is counterintuitive, because we are taught to write code that is elegant and readable. But in SQL, elegance is not just aesthetic. It is structural. The database rewards expressions that leave doors open for optimization.


Key Takeaways

  • Prefer searchable predicates over computed predicates. Write conditions directly against indexed columns whenever possible.
  • Filter early, format late. Use WHERE to reduce rows before sorting, grouping, or string formatting.
  • Avoid hiding indexed columns inside functions, arithmetic, or negation. If you transform the column first, the engine may lose the index.
  • Use prefix wildcards carefully. LIKE 'abc%' is usually friendlier to indexes than LIKE '%abc'.
  • Treat aliases as part of query design, not decoration. Clear naming helps you reason about what belongs in search logic versus presentation logic.

A New Way to Think About Efficient SQL

The deepest lesson here is that performance is not an afterthought bolted onto correctness. Performance is what correctness looks like when expressed in the database's native grammar. A query can be logically perfect and still be operationally clumsy. The goal is not merely to ask the right question, but to ask it in a way that leaves the engine maximum freedom to answer efficiently.

That reframes SQL from a mere data retrieval tool into a partnership between human intent and machine execution. Humans supply meaning. The database supplies strategy. When the query is written well, those two forms of intelligence reinforce each other.

So the next time a query feels "obvious," ask a harder question: obvious to whom? If it is obvious to you but opaque to the optimizer, you have written a sentence. If it is obvious to both, you have written a good query.

And that may be the most useful definition of optimization in SQL: the art of making intention searchable.

Sources

← Back to Library

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 🐣