简体   繁体   中英

sql queries : IN vs equal

I have code which generates a sql statement that looks like such:

SELECT * FROM items WHERE id IN (X, Y, Z)

where x, y, z are ints.

There is a case where my array only has one integer causing this to be generated

SELECT * FROM items WHERE id in (X)

Ideally this should be where id = x

Are there any performance implications calling in instead of = when there's only 1 item?

For one item it won't have an impact. I tested it on a table that has 25000 rows and about 15 columns (no large text columns).

If I use this:

EXPLAIN  
SELECT
    *
FROM users
WHERE
    user_id = 10104

The query plan is simple:

Index Scan using users_pkey on users  (cost=0.29..8.30 rows=1 width=147)
  Index Cond: (user_id = 10104)

Since user_id is a primary key it will use it.

Now second query:

EXPLAIN  
SELECT
    *
FROM users
WHERE
    user_Id IN(10104)

Yields EXACTLY the same query plan because the database knows those are equal queries in the end.

I would advise you to run the same queries (with EXPLAIN ) on your tables and have a look for yourself, that's because I don't know the structures of your tables, indexes, etc.

Run the same comparison for a query with more than one option, then things get interesting but since your question is about just one item you can sleep well knowing it will not have an impact.

Even if it had, in my opinion it would be so small that you shouldn't waste too much time thinking about what is the best practice here. Make sure your code is readable and well-written and that's already a step in the right direction

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