简体   繁体   English

将postgres中的简单更新语句加速一百万行

[英]Speed up simple update statement in postgres for 1 million rows

I have a very simple sql update statement in postgres. 我在postgres中有一个非常简单的sql更新语句。

UPDATE p2sa.observation SET file_path = replace(file_path, 'path/sps', 'newpath/p2s')

The observation table has 1513128 rows. 观察表有1513128行。 The query so far has been running for around 18 hours with no end in sight. 到目前为止,该查询已经运行了大约18个小时,而且还没有结束。

The file_path column is not indexed so I guess it is doing a top to bottom scan but it seems a bit excessive the time. file_path列未建立索引,因此我想它正在执行从上到下的扫描,但时间似乎有点过多。 Probably replace is also a slow operation. 可能更换也很慢。

Is there some alternative or better approach for doing this one off kind of update which affects all rows. 是否有其他替代方法或更好的方法来执行这种一次性更新,从而影响所有行。 It is essentially updating an old file path to a new location. 它实际上是将旧文件路径更新到新位置。 It only needs to be updated once or maybe again in the future. 以后只需要更新一次或也许再次更新。

Thanks. 谢谢。

In SQL you could do a while loop to update in batches. 在SQL中,您可以进行while循环以批量更新。

Try this to see how it performs. 尝试此操作以查看其性能。

Declare @counter int 
Declare @RowsEffected int 
Declare @RowsCnt int 
Declare @CodeId int 
Declare @Err int
DECLARE @MaxNumber int = (select COUNT(*) from p2sa.observation)
SELECT @COUNTER = 1
SELECT @RowsEffected = 0


WHILE ( @RowsEffected < @MaxNumber)
BEGIN 
SET ROWCOUNT 10000


UPDATE p2sa.observation 
SET file_path = replace(file_path, 'path/sps', 'newpath/p2s')
where file_path != 'newpath/p2s'

SELECT @RowsCnt = @@ROWCOUNT ,@Err = @@error 
IF @Err <> 0 
BEGIN 
Print 'Problem Updating the records' 
BREAK
END 
ELSE 

SELECT @RowsEffected = @RowsEffected + @RowsCnt 
PRINT 'The total number of rows effected :'+convert(varchar,@RowsEffected) 

            /*delaying the Loop for 10 secs , so that Update is completed*/    

     WAITFOR DELAY '00:00:10'         
 END
 SET ROWCOUNT 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM