NOWAIT is an optional clause appended to lock-acquiring statements such as SELECT … FOR UPDATE, SELECT … FOR SHARE, and LOCK TABLE. When present, the database tries to obtain the requested lock only once. If the lock is already held by another transaction, the statement aborts right away with a lock-related error instead of blocking until the lock becomes available. This behavior is crucial for building low-latency, deadlock-resistant applications and for keeping interactive sessions responsive. NOWAIT is not part of the ANSI SQL standard, but several major databases implement it with similar semantics. In PostgreSQL, a NOWAIT failure raises the SQLSTATE 55P03 (lock_not_available). Oracle and SQL Server expose the same idea in slightly different syntaxes, but the outcome is identical: fail fast when contention occurs. Be sure to handle the possible error in application code and to understand that NOWAIT only affects lock acquisition, not statement execution once the lock is granted.
SELECT FOR UPDATE, SKIP LOCKED, LOCK TABLE, NOWAIT table hint (SQL Server), lock_timeouts
PostgreSQL 9.3; Oracle 9i; SQL Server 2005 (NOWAIT hint)
The statement acquires the lock instantly and proceeds to return the requested rows or confirmation, just like a normal locking statement.
PostgreSQL raises SQLSTATE 55P03 (lock_not_available) with the message "could not obtain lock on row/table" depending on the lock type.
No. In PostgreSQL you must choose one or the other. NOWAIT aborts on the first locked row, while SKIP LOCKED silently ignores locked rows.
Wrap the NOWAIT statement in application code that catches the lock_not_available error, sleeps (optionally with back-off), and retries the statement until it succeeds or a maximum number of attempts is reached.