简体   繁体   中英

sql select condition performance

I have a table 'Tab' with data such as:

 id |  value
---------------
 1  |  Germany
 2  |  Argentina
 3  |  Brasil
 4  |  Holland

What way of select is better by perfomane?

1. SELECT * FROM Tab WHERE value IN ('Argentina', 'Holland')

or

2. SELECT * FROM Tab WHERE id IN (2, 4)

I suppose that second select would be faster, because int comparison is faster than string. Is that true for MS SQL?

This is too long for a comment.

This is a premature optimization. The comparison between integers and strings is generally going to have a minimal impact on query performance. The drivers of query performance are more along the lines of tables sizes, query plans, available memory, and competition for resources.

In general, it is a good idea to have indexes on columns used for either comparison. The first column looks like a primary key, so it automatically gets an index. The string column should have an index built on it. In general, indexes built on an integer column will have marginally better performance compared to integers built on variable length string columns. However, this type of performance difference really makes a difference only in environments with very high levels of transactions (think thousands of data modification operations per second).

You should use the logic that best fits the application and worry about other aspects of the code.

To answer the simple question yes option 2 SELECT * FROM Tab WHERE id IN (2, 4) would be faster as you said because int comparison is faster.

One way to speed it up is to add indexes to your columns to speed up evaluation, filtering, and the final retrieval of results.

If this table was to grow even more you should also not SELECT * but SELECT id, value otherwise you may be pulling more data than you need.

You can also speed up your query's buy adding WITH(NOLOCK) as the speed of your query might be affected by other sessions accessing the tables at the same time. For example SELECT * FROM Tab WITH(NOLOCK) WHERE id IN (2, 4) . As mentioned below though adding nolock is not a turbo and should only be used in appropriate situations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM