Performance issue in update query

你。 提交于 2019-12-02 20:55:56
Craig Ringer

In rough order of slower to faster:

  • 200 Individual queries, each in their own transaction
  • 200 Individual queries, all in one transaction
  • 1 big query with WHERE ... IN (...) or WHERE EXISTS (SELECT ...)
  • 1 big query with an INNER JOIN over a VALUES clause
  • (only faster for very big lists of values): COPY value list to a temp table, index it, and JOIN on the temp table.

If you're using hundreds of values I really suggest joining over a VALUES clause. For many thousands of values, COPY to a temp table and index it then join on it.

An example of joining on a values clause. Given this IN query:

SELECT *
FROM mytable
WHERE somevalue IN (1, 2, 3, 4, 5);

the equivalent with VALUES is:

SELECT *
FROM mytable
INNER JOIN (
  VALUES (1), (2), (3), (4), (5)
) vals(v)
ON (somevalue = v);

Note, however, that using VALUES this way is a PostgreSQL extension, wheras IN, or using a temporary table, is SQL standard.

See this related question:

Definitely you should use WHERE IN operator. Making 200 queries is much slower than one bigger. Remember, when you sending query to database, there is additional time needed to communicate between server and DB and this will crush your performance.

Definitely IN is more powerful, but again the number of match to check in IN will make performance issue.

So, I will suggest to use IN but with BATCH, as in if you have 200 record to update then part in 50 each and then make 4 UPDATE query, or something like that.

Hope it helps...!!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!