SQL Performance UNION vs OR

MysqlSqlPerformanceUnion

Mysql Problem Overview


I just read part of an optimization article and segfaulted on the following statement:

> When using SQL replace statements using OR with a UNION:

> select username from users where company = ‘bbc’ or company = ‘itv’;

> to:

> select username from users where company = ‘bbc’ union select username from users where company = ‘itv’;

From a quick EXPLAIN:

Using OR:

enter image description here

Using UNION:

enter image description here

Doesn't this mean UNION does in double the work?

While I appreciate UNION may be more performant for certain RDBMSes and certain table schemas, this is not categorically true as the author suggestions.

Question

Am I wrong?

Mysql Solutions


Solution 1 - Mysql

Either the article you read used a bad example, or you misinterpreted their point.

select username from users where company = 'bbc' or company = 'itv';

This is equivalent to:

select username from users where company IN ('bbc', 'itv');

MySQL can use an index on company for this query just fine. There's no need to do any UNION.

The more tricky case is where you have an OR condition that involves two different columns.

select username from users where company = 'bbc' or city = 'London';

Suppose there's an index on company and a separate index on city. Given that MySQL usually uses only one index per table in a given query, which index should it use? If it uses the index on company, it would still have to do a table-scan to find rows where city is London. If it uses the index on city, it would have to do a table-scan for rows where company is bbc.

The UNION solution is for this type of case.

select username from users where company = 'bbc' 
union
select username from users where city = 'London';

Now each sub-query can use the index for its search, and the results of the subquery are combined by the UNION.


An anonymous user proposed an edit to my answer above, but a moderator rejected the edit. It should have been a comment, not an edit. The claim of the proposed edit was that UNION has to sort the result set to eliminate duplicate rows. This makes the query run slower, and the index optimization is therefore a wash.

My response is that that the indexes help to reduce the result set to a small number of rows before the UNION happens. UNION does in fact eliminate duplicates, but to do that it only has to sort the small result set. There might be cases where the WHERE clauses match a significant portion of the table, and sorting during UNION is as expensive as simply doing the table-scan. But it's more common for the result set to be reduced by the indexed searches, so the sorting is much less costly than the table-scan.

The difference depends on the data in the table, and the terms being searched. The only way to determine the best solution for a given query is to try both methods in the MySQL query profiler and compare their performance.

Solution 2 - Mysql

Those are not the same query.

I don't have much experience with MySQL, so I am not sure what the query optimizer does or does not do, but here are my thoughts from my general background (primarily ms sql server).

Typically, the query analyzer can take the above two queries and make the exact same plan out of them (if they were the same), so it wouldn't matter. I would suspect that there is no performance difference between these queries (which are equivalent)

select distinct username from users where company = ‘bbc’ or company = ‘itv’;

and

select username from users where company = ‘bbc’ 
union
select username from users where company = ‘itv’;

Now, the question is, would there be a difference between the following queries, of which I actually don't know, but I would suspect that the optimizer would make it more like the first query

select username from users where company = ‘bbc’ or company = ‘itv’;

and

select username from users where company = ‘bbc’ 
union all
select username from users where company = ‘itv’;

Solution 3 - Mysql

It depends on what the optimizer ends up doing based on the size of the data, indexes, software version, etc.

I would guess that using OR would give the optimizer a better chance at finding some efficiencies, since everything is in a single logical statement.

Also, UNION has some overhead, since it creates a reset set (no duplicates). Each statement in the UNION should execute pretty quickly if company is indexed... not sure it'd really be doing double the work.

Bottom line

Unless you really have a burning need to squeeze every bit of speed out of your query, it's probably better to just go with the form that best communicates your intention... the OR

Update

I also meant to mention IN. I believe the following query will give better performance than the OR (it's also the form I prefer):

select username from users where company in ('bbc', 'itv');

Solution 4 - Mysql

In almost all cases, the union or union all version is going to do two full table scans of the users table.

The or version is much better in practice, since it will only scan the table once. It will also use an index only once, if available.

The original statement just seems wrong, for just about any database and any situation.

Solution 5 - Mysql

Bill Karwin's answer is pretty right. When the both part of the OR statement has its own index, it's better doing union because once you have a small subset of results, it's easier to sort them and eliminate duplicates. Total cost is almost less than using only one index (for one of the column) and table scan for the other column (because mysql only uses one index for one column).

It depends of the table's structure and needs generally but in large tables union gave to me better results.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJason McCrearyView Question on Stackoverflow
Solution 1 - MysqlBill KarwinView Answer on Stackoverflow
Solution 2 - MysqlDarren KoppView Answer on Stackoverflow
Solution 3 - MysqlDavid JView Answer on Stackoverflow
Solution 4 - MysqlGordon LinoffView Answer on Stackoverflow
Solution 5 - MysqlÇağatay GürtürkView Answer on Stackoverflow