SQL SLEEP, pg_sleep and WAITFOR DELAY
A deliberate pause is handy for reproducing lock waits, testing client timeouts and spacing out batch jobs.
- Categoria
- System & session
- Returns
0 (MySQL), void (PostgreSQL)- In this category
- 12 of 13
Sintaxe
SLEEP(seconds)
pg_sleep(seconds)
WAITFOR DELAY 'hh:mm:ss'
DBMS_SESSION.SLEEP(seconds)
Each block is a separate form. The support table and the examples show which engine takes which.
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Different name or syntax | WAITFOR DELAY 'hh:mm:ss[.mmm]', a statement, not a function |
| PostgreSQL | Different name or syntax | pg_sleep(seconds); pg_sleep_for(interval) and pg_sleep_until(timestamp) |
| MySQL | Sim | SLEEP(seconds) returns 0, or 1 when interrupted |
| SQLite | Not built in | none in SQL; sqlite3_sleep() is a C API call |
| Oracle | Different name or syntax | DBMS_SESSION.SLEEP(seconds) in PL/SQL from 18c; DBMS_LOCK.SLEEP before that |
Exemplos
MySQL
SELECT SLEEP(0.5) AS slept; -- 0, after half a second
PostgreSQL
SELECT pg_sleep_for('500 milliseconds');
SQL Server
WAITFOR DELAY '00:00:00.500'; SELECT 'done' AS status;
Oracle
BEGIN DBMS_SESSION.SLEEP(0.5); END; /
Bom saber
- A sleeping session keeps its transaction and locks. Sleep inside a transaction and every writer waiting for those rows waits as well.
- MySQL evaluates SLEEP once per row: SELECT SLEEP(1) FROM t with ten rows takes about ten seconds.
- WAITFOR DELAY takes a time string, not a number: WAITFOR DELAY '00:00:05' waits five seconds.
Questions about SLEEP
Why would you sleep inside SQL?
To hold a lock while you test what another session does, to check that an application's query timeout fires, or to throttle a loop that deletes in batches.
How do I pause in SQLite?
Not from SQL. Sleep in the host program between statements, or call sqlite3_sleep() from C.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.