Home >Database >Mysql Tutorial >How Can I Find Gaps in a MySQL Auto-Increment Sequence?

How Can I Find Gaps in a MySQL Auto-Increment Sequence?

Susan Sarandon
Susan SarandonOriginal
2025-01-12 06:10:45268browse

How Can I Find Gaps in a MySQL Auto-Increment Sequence?

Detecting Missing Numbers in MySQL Auto-Increment Columns

Many MySQL tables utilize auto-increment columns to ensure unique identification. However, data deletion or other operations can leave gaps in the sequential numbering. This query effectively pinpoints these gaps within a defined range:

<code class="language-sql">SELECT (t1.id + 1) AS gap_starts_at,
       (SELECT MIN(t3.id) - 1 FROM arrc_vouchers t3 WHERE t3.id > t1.id) AS gap_ends_at
FROM arrc_vouchers t1
WHERE NOT EXISTS (SELECT t2.id FROM arrc_vouchers t2 WHERE t2.id = t1.id + 1)
HAVING gap_ends_at IS NOT NULL;</code>

The query's output consists of:

  • gap_starts_at: Indicates the starting point of a missing number sequence.
  • gap_ends_at: Shows the endpoint of the missing sequence.

The above is the detailed content of How Can I Find Gaps in a MySQL Auto-Increment Sequence?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn