Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL efficiency - [=] vs [in] vs [like] vs [matches]

Just out of curiosity, I was wondering if there are any speed/efficiency differences in using [=] versus [in] versus [like] versus [matches] (for only 1 value) syntax for sql.

select field from table where field = value;

versus

select field from table where field in (value);

versus

select field from table where field like value;

versus

select field from table where field matches value;
like image 681
CheeseConQueso Avatar asked Jul 28 '10 13:07

CheeseConQueso


2 Answers

it depends on the underlying SQL engine. In MS-SQL, for example (according to the query planner output), IN clauses are converted to =, so there would be no difference

like image 157
Steven A. Lowe Avatar answered Oct 04 '22 02:10

Steven A. Lowe


I will add to that also exists and subquery.

But the performance depends on the optimizer of the given SQL engine.

In oracle you have a lot of differences between IN and EXISTS, but not necessarily in SQL Server.

The other thing that you have to consider is the selectivity of the column that you use. Some cases show that IN is better.


But you have to remember that IN is non-sargable (non search argument able) so it will not use the index to resolve the query, the LIKE and = are sargable and support the index


The best ? You should spend some time to test it in your environment

like image 21
Damian Leszczyński - Vash Avatar answered Oct 04 '22 03:10

Damian Leszczyński - Vash