开发者

Maximum length of an SQL Query

开发者 https://www.devze.com 2023-02-09 13:34 出处:网络
SELECT f.* FROM feeds f, user_feeds uf WHERE (f.id=uf.feed_id and uf.user_id in (1,2,5,6,23,45)) ORDER BY created_at DESC
SELECT f.* 
FROM feeds f, 
     user_feeds uf 
WHERE (f.id=uf.feed_id and uf.user_id in (1,2,5,6,23,45)) 
ORDER BY created_at DESC

This is a query used to construct a user's feeds. The issue I have with this query is that the "uf.user_id in ()" increases as the number of users the user follows increases开发者_StackOverflow中文版.

What is the allowed max length of an SQL query? Is there a better way to implement the above query?

Note: I am using ActiveRecord and Postgres.


The maximum length of a query that PostgreSQL can process is 2147483648 characters (signed 4-byte integer; see src/include/lib/stringinfo.h).


To avoid the query size, you could replace the IN (1, 2) with IN (select followed_id from following where follower_id = ?) or whatever the appropriate query would be to find the ids of the followed users from the follower's id.


While there is no (real) limit on the length of the query string, there is a limit on the number of IN (x,y,z...) clauses: 10000, configurable in the postgres.ini-file:

See: http://grokbase.com/t/postgresql/pgsql-general/061mc7pxg6/what-is-the-maximum-length-of-an-in-a-b-c-d-list-in-postgresql :

"In 7.4 and earlier it depends on the max_expr_depth setting." ... "In 8.0 and later max_expr_depth is gone and the limit depends on max_stack_depth."


You could consider using a subquery to construct the IN portion of your original WHERE clause. So the result would look something like this:

"SELECT f.* FROM feeds f, user_feeds uf WHERE (f.id=uf.feed_id and uf.user_id in (SELECT followed where follower = id)) ORDER BY created_at DESC"

Obviously the subquery isn't right as I posted it, but that should give you the general idea.


Use a correlated sub-query. If you have a table that holds the users a member follows your query text won't grow.

For example:

SELECT f.* 
FROM feeds f, 
     user_feeds uf 
WHERE f.id=uf.feed_id 
  AND EXISTS (SELECT 'X'
              FROM follows
              WHERE follows.user_id = uf.user_id) 
ORDER BY created_at DESC;
0

精彩评论

暂无评论...
验证码 换一张
取 消