0

I've a bit older project. It uses mysql 5.5.59. In the beginning, with only some rows in the table, the performance was good. But now the table has about 80.000 rows (imho: it's still very small).

But actually we face some performance problems so my task is to optimize SQL. I figured outsomething very curious which I cannot explain: UNION is faster than OR!

Here's my simplyfied OR statement:

SELECT SQL_NO_CACHE SQL_CALC_FOUND_ROWS field1, field2, field3
FROM tablename
WHERE field1 = 'some_value' OR field2 = 'some_value'
ORDER BY field3;

And this is my simplyfied UNION statement:

SELECT SQL_NO_CACHE SQL_CALC_FOUND_ROWS *
FROM (
SELECT field1, field2, field3
FROM tablename
WHERE field1 = 'some_value') a1 
UNION (
SELECT field1, field2, field3
FROM tablename
WHERE field2 = 'some_value')
ORDER BY field3;

Theres an index on field1 and field2.

I testet on mysql-cli with SQL_NO_CACHE to block the query cache from mysql and got following results: the UNION statement needs 0.00 sec, the OR-Statement needs 0.21 sec

Can anyone eyplain this behavior? Or is there a way to optimize an OR-Statement?

Marco
  • 3,470
  • 4
  • 23
  • 35
  • 1
    It is totally based on the situation and indexes define on the table... Very good article: http://www.sql-server-performance.com/2011/union-or-sql-server-queries/ – Mittal Patel Feb 22 '18 at 10:44
  • 3
    If you have separate indexes (one on each column) then union can use those indexes, but using OR index can't be used. Please see (or share) explain plans to see what is really happening. This is explained in answer under link provided by @Mittal – Edgars T. Feb 22 '18 at 10:49
  • Just a detail, your table has _columns_, not _fields_. – jarlh Feb 22 '18 at 10:50
  • @Mittal: I haven't found the article before posting my question, but you are right: The accepted answer in https://stackoverflow.com/questions/13750475/sql-performance-union-vs-or explains this problem. – Marco Feb 22 '18 at 10:53
  • to bad that article is for SQL-server this question is tagged MySQL @Mittal – Raymond Nijland Feb 22 '18 at 11:00

0 Answers0