views:

83

answers:

4

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;
+3  A: 

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

Steven A. Lowe
+1  A: 

normally the "in" statement is used when there are several values to be compared. The engine walks the list for each value to see if one matches. if there is only one element then there is no difference in time vs the "=" statement.

the "like" expression is different in that is uses pattern matching to find the correct values, and as such requires a bit more work in the back end. For a single value, there wouldn't be a significant time difference because you only have one possible match, and the comparison would be the same type of comparison that would occur for "=" and "in".

basically, no, or at least the difference is so insignificant that you wouldn't notice.

Scott M.
+1  A: 

The best practice for any question about what would be faster, is to measure. SQL engines are notoriously difficult to predict. You can look at the output of EXPLAIN PLAN to get a sense of it, but in the end, only measuring the performance on real data will tell you what you need to know.

In theory, a SQL engine could implement all three of these exactly the same, but they may not.

Ned Batchelder
+1  A: 

A will add to that also exists and sub query.

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

In oracle you have a lot difference between IN and EXISTS, but in SQL Server not necessary.

The other thing that you have to consider is the selectivity of the column that You use. Some case show that in is better.


But You have to remember that IN is nonsargable (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

Vash