How to Fix MySQL Error 3066 (ER_AGGREGATE_IN_ORDER_NOT_SELECT)

Published
Length
3 min read

Luis Felipe Dias

All posts

You get mysql error 3066 when a query sorts by an aggregate function missing from the select list. You can fix it by adding the aggregate expression to the select list or using a subquery. This failure uses the official symbol ER_AGGREGATE_IN_ORDER_NOT_SELECT and returns SQLSTATE HY000. It happens when your query combines distinct results with a sort rule that aggregates hidden values. The database engine blocks the query because it cannot sort unique rows by an uncalculated summary value. Unde

Your coding agents run with your access.

Claude Code reaches prod with a developer's credentials, and approval prompts get clicked through. hoop.dev checks every query, masks sensitive data, and holds risky changes for a human.

You get mysql error 3066 when a query sorts by an aggregate function missing from the select list. You can fix it by adding the aggregate expression to the select list or using a subquery.

This failure uses the official symbol ER_AGGREGATE_IN_ORDER_NOT_SELECT and returns SQLSTATE HY000. It happens when your query combines distinct results with a sort rule that aggregates hidden values. The database engine blocks the query because it cannot sort unique rows by an uncalculated summary value. Understanding how the engine processes distinct rows and sorting rules helps you fix this issue fast.

Root causes of mysql error 3066 in the database engine

The database engine processes query steps in a strict order. First, it filters rows and groups data. Next, it calculates aggregate values and removes duplicate rows when you request distinct results. Last, the engine sorts the final output based on your order clause.

When you ask for unique rows, the engine drops columns that are not in the select list. If your sort clause uses an aggregate function on a dropped column, the engine gets stuck. Multiple source rows might merge into a single unique output row. The engine does not know how to calculate an aggregate sort value after merging those rows.

To prevent wrong data, the server stops and throws error code 3066. The official message states that the sort expression is not in the select list and contains an aggregate. It also notes that this query pattern conflicts with the strict distinct mode active on the server. Modern database setups enable this strict validation rule by default to keep query results accurate and predictable.

How to diagnose and fix the failure in production

To find the broken query, check your app error logs for SQLSTATE HY000 and code 3066. Look at the exact position number mentioned in the error message. That number tells you which item in your sort clause caused the failure.

Do not fix this problem by turning off strict SQL modes in your server settings. Disabling safety checks across the database can cause silent data bugs and random sort orders. Also, do not grant developers broad admin roles to change session rules in production.

Just-in-Time Access + MySQL Access Governance: architecture patterns and best practices

Continue reading? Get the full guide.

Free. No spam. Unsubscribe anytime.

Instead, fix the query logic in your app code. The simplest fix is to add the aggregate function from your sort clause into your select list. Once the aggregate value is part of the output, the engine can sort the distinct rows safely.

If your app cannot accept an extra column in the result set, rewrite the query. Replace the distinct keyword with a group by clause that lists your selected columns. Grouping rows before sorting lets the engine calculate the aggregate sort value without conflict. You can also wrap the main query in a subquery or common table expression. Calculate the aggregate inside the inner query, then select only the needed columns in the outer query.

Preventing sorting errors during schema and query reviews

Many teams hit this error after a database upgrade or when moving from test to production. A local database might run with relaxed SQL rules, while production enforces strict checks. You should match your test database rules to your production rules so bad queries fail early.

When engineers need to test query fixes against real data, control how they run those checks. Use a proxy layer that applies data masking to rewrite matched fields like emails and card numbers. This setup lets developers debug grouping and sorting logic without exposing sensitive customer records during testing.

Add wire guardrails and masking beside MySQL

Database grants and TLS setup decide who can reach MySQL. Even so, an open session can run broad updates or read raw personal data from allowed tables. In practice, hoop.dev sits inline in the wire protocol beside the database as a sidecar for your MySQL. On every production query an agent or engineer sends, hoop.dev decides to pass, mask, block, or escalate it for human review.

With hoop.dev MySQL support, guardrails refuse bad queries before they run or hold risky calls for approval, while data masking rewrites matched sensitive values in result rows in memory. Furthermore, hoop.dev holds SOC 2 Type II and generates evidence for GDPR, HIPAA, and PCI DSS programs. Read the docs and source on GitHub.

Frequently asked questions

What does ER_AGGREGATE_IN_ORDER_NOT_SELECT mean in plain terms?

It means your query sorts unique results using a summary function like count or max that you did not select. The database cannot calculate that summary value after it merges duplicate rows.

Should I disable strict SQL modes to bypass error 3066?

No, turning off strict validation checks is risky for production data. Without this check, the database picks random values during sorting and returns inconsistent results to your app.

How can I sort by an aggregate without changing the returned columns?

Switch from using the distinct keyword to a group by clause on your selected columns. You can also calculate the aggregate inside a subquery and filter the columns in the outer query.

The query runs. The emails stay hidden.