GET_LOCK()

Acquires a named user-level advisory lock for the current session, waiting up to the requested timeout.

Syntax

GET_LOCK(name, timeout)

Arguments

Argument

Description

name

Lock name. Names are case-insensitive, limited to 64 characters, and cannot contain NUL bytes.

timeout

Maximum number of seconds to wait. Use 0 for an immediate attempt.

Return Value

  • Returns 1 when the lock is acquired.

  • Returns 0 when the timeout expires before the lock becomes available.

  • Returns NULL for invalid input or an execution error.

Usage Notes

  • Locks belong to sessions, not transactions; committing or rolling back does not release them.

  • Repeated acquisition by the same session is reference-counted. Call RELEASE_LOCK() once per acquisition, or use RELEASE_ALL_LOCKS().

  • Source evidence: test/distributed/cases/function/user_lock.sql.

Examples

DROP DATABASE IF EXISTS get_lock_demo;
CREATE DATABASE get_lock_demo;
USE get_lock_demo;

SELECT GET_LOCK('daily_import', 0) AS acquired;
SELECT IS_USED_LOCK('daily_import') = CONNECTION_ID() AS held_by_current_session;
SELECT RELEASE_LOCK('daily_import') AS released;

DROP DATABASE get_lock_demo;

See Also