Maximum number of values we can have in IN clause

Question:

Is there a limit to the maximum number of values we can have in the in clause

sql_query = """SELECT * FROM table1
               WHERE column1 IN %(list_of_values)s
               ORDER BY CASE
               WHEN column2 LIKE 'a%' THEN 1
               WHEN column2 LIKE 'b%' THEN 2
               WHEN column2 LIKE 'c%' THEN 3
               ELSE 99 END;"""

params = {'list_of_values': list_of_values}

cursor.execute(sql_query, params)
Asked By: Tanu

||

Answers:

The amount of values that can be used in an IN clause is not restricted, however, MySQL does have a maximum query string length restriction, which may inadvertently reduce the number of variables in an IN clause. The value of the system variable max_allowed_packet which specifies the maximum size of a packet or a large column value controls this limit. The default value of 4MB may restrict the range of values that can be used in an IN clause.

See the documentation about MySQL’s max_allowed_packet here.

Some other databases, however, may have some restriction. Oracle Database 12c Release 1 documentation says that the number of elements in the expression list is limited to 1000.

Answered By: Subhash Prajapati

There is no fixed limit of values in the IN clause, neither in 5.7 or 8.0. The theoretical limit depends on the length of your SQL statement and the value of max_allowed_packet.

This is also documented in the MySQL documentation:

"The number of values in the IN() list is only limited by the max_allowed_packet value."

Answered By: Georg Richter
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.