75

I have a 500,000 line SQL script:

UPDATE users SET region_id = 9814746 WHERE id = 101 AND region_id IS null;
UPDATE users SET region_id = 9814731 WHERE id = 102 AND region_id IS null;
UPDATE users SET region_id = 3470676 WHERE id = 103 AND region_id IS null;

I want to INSERT a delay of 10 seconds every 50 lines. Does pgsql have a waitfor statement like t-sql.

Thanks.

5 Answers 5

124

Does pgsql have a waitfor statement like t-sql.

Yes, pg_sleep:

pg=> SELECT pg_sleep(10);
 pg_sleep 
----------

(1 row)
Sign up to request clarification or add additional context in comments.

1 Comment

If for some reason you want to run this statement as part of single select statement, you can use select data.id from (select id, pg_sleep(10) from sometable) AS data;
40

You could call the pg_sleep function with the PERFORM statement since we don't care about returning values:

PERFORM pg_sleep(10);

2 Comments

@dannymo This should work: DO $$ BEGIN PERFORM pg_sleep(1); END $$;
what specifically perform does?
6

You can use pg_sleep() and pg_sleep_for() to delay 10 seconds as shown below according to Delaying Execution:

SELECT pg_sleep(10);
SELECT pg_sleep_for('10 seconds');
SELECT pg_sleep_for('10 second');

In addition, you can use pg_sleep_until() to delay until some time as shown below:

SELECT pg_sleep_until('today 21:45');
SELECT pg_sleep_until('tomorrow 03:00');

Comments

1

As pilcrow says that is the easiest way. If you do not want to see the results back, just turn off display before running pg_sleep like this -->

\pset tuples_only on
select pg_sleep(10) ;
\pset tuples_only off

Comments

0

Not to my knowledge.

You could do something in the shell, piping your SQL through a simple script and then into PostgreSQL. E.g. with Perl:

cat regionupdates.sql | perl -e '$i = 1; while(<STDIN>) { $i++; print $_; if ($i % 50 == 0) { sleep 10; } }' | psql -d MYDB -L output.txt

BTW: I see you asked a very similar question before. It would be nice if you could accept the answers you found solved your problem:

Begin...commit every 50 rows

2 Comments

I included the cat as the source of the SQL may quite easily not be a file, but be generated by another program or shell script, so the structure of the command could easily be altered. But I take your point in general.
Hmm, not sure why you got the downvote -- stylistic uses of cat aside. ;-) If I had an upvote for every time I filtered SQL statements through perl/awk/you-name-it to get the behavior I wanted, I'd be Jon Skeet. +1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.