Sample Header Ad - 728x90

Why is LIMIT disallowed in IN subqueries in MySQL?

0 votes
4 answers
216 views
--- ### Please read carefully. This question is _not_ about workarounds or alternative ways to achieve LIMIT in IN subqueries! --- It’s a well-known and well-documented that there are [a number of restrictions on subqueries](https://dev.mysql.com/doc/mysql-reslimits-excerpt/8.0/en/subquery-restrictions.html) in MySQL (and MariaDB). Of the restrictions listed in the documentation, the reasoning behind most is either quite logical (e.g., you cannot modify and select from the same table in the same query) or explained on the page. The only restriction that _doesn’t_ provide a reasoning in the documentation is also the most common one to come up against, namely that you cannot LIMIT a subquery with certain operators, most commonly IN. This is invalid:
SELECT * FROM a WHERE b_id IN (SELECT id FROM b ORDER BY c LIMIT 5)
There are any number of questions strewn across the Internet (including on this site) looking for alternative ways to achieve the same effect, but that’s not what I’m asking for here – I know you can just wrap it in another subquery and it works. What I’m puzzled by is the fact that I cannot find any explanation as to **why** this restriction exists to begin with. I’m guessing it’s not part of the SQL standard, since limiting subqueries in this way is perfectly valid in other engines, like SQL Server and (as far as I can tell) PostgreSQL. So why did the developers of MySQL (and MariaDB) decide that using LIMIT in subqueries with operators like IN should be disallowed? Has anyone from the developer team ever mentioned or explained the choice?
Asked by Janus Bahs Jacquet (111 rep)
Apr 3, 2025, 01:50 PM
Last activity: Apr 20, 2025, 10:29 PM