views:

95

answers:

4

Please tell me from experience with using the "IN clause" in a MySQL query is considered to be too large of a list to push through to be considered good practice?

Example scenario is I have a string of user ID numbers that I will pull from a cache, it can range from anywhere from 1 number all the way up to being 5,000 numbers in this list and I will use a mysql query with this list like this example;

SELECT column FROM table 
WHERE userid 
IN ( 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 )

Can you give me your thoughts on this issue please?

A: 

I would not recommend using the in clause, the query will execute allot faster if you used a join instead.

What is your table structure, I'm guessing you have a table storing friend relations, can't you join on that instead?

SELECT * --you columns
FROM FriendLinks fl
Inner JOIN Users u on  fl.friendid = u.id
WHERE u.id = <your id>

or something like that

monkey_p
I have been experimenting with different joins and methods of doing this for over a year now, my results if a users has like under 1,000 friends, the IN clause works faster and over that it seems to work faster with a JOIN but now my site is starting to use things that already have 2-3 joins so I didnt want to add the friend join to them as well. Also another reason is soon I will be caching the friend list in memcache or as an array in a file cache, so once it's cached I can't use a join?
jasondavis
A: 

As long as your userid field is indexed, sounds like a good option.

Anyway, the real question here would be comparing the performance of IN against some other alternative. If that's the only way to get your data, there's not much you can do about it

Jorge Bernal
+2  A: 

It should be noted that some databases have limits on the number of entries within an IN clause - Oracle versions <= 10 are limited to 1000. I'm not sure about v11.

Good to know I wonder if mysql has a limit
jasondavis
A: 

from a similar question, max length is configurable with a limit of 1GB in 5.0 according to mysql docs

larham1