// dialect comparison

REINDEX and ALTER INDEX REBUILD in every SQL dialect

Indexes bloat after churn. Each engine has its own rebuild verb, and one of them (MySQL) rebuilds the whole table instead.

Filed under Índices

The verdict

Five engines, four commands and one workaround: ALTER INDEX REBUILD (SQL Server, Oracle), REINDEX (PostgreSQL, SQLite), and MySQL only rebuilds via table-level DDL. Concurrency needs the ONLINE/CONCURRENTLY keyword on each.

Where they differ

Rebuilding rewrites the index structure compactly. The portability story is mixed: same idea, five different commands, and concurrency guarantees differ per engine.

How each engine writes it

SQL Server

ALTER INDEX idx_orders_customer ON orders REBUILD;

Online with ONLINE = ON, else the table is locked. REORGANIZE is the lightweight online alternative for light fragmentation.

PostgreSQL

REINDEX INDEX idx_orders_customer;

Takes an exclusive lock while building; REINDEX INDEX CONCURRENTLY avoids blocking writes (PostgreSQL 12+).

MySQL

ALTER TABLE orders ENGINE=InnoDB;

InnoDB has no per-index rebuild command. A null ALTER TABLE ... ENGINE=InnoDB, or OPTIMIZE TABLE (which InnoDB maps to the same recreate), rebuilds the table and all its indexes as online DDL.

SQLite

REINDEX idx_orders_customer;

REINDEX works on an index, table or the whole database (REINDEX; with no argument).

Oracle

ALTER INDEX idx_orders_customer REBUILD;

Add ONLINE to keep DML running (Enterprise Edition). For light cleanup, ALTER INDEX ... COALESCE merges sparse leaf blocks without a rebuild, and SHRINK SPACE also releases space in ASSM tablespaces.

Questions that come up

How do I know an index needs rebuilding?

SQL Server: sys.dm_db_index_physical_stats avg_fragmentation_in_percent. PostgreSQL: pgstattuple bloat. InnoDB: innodb_index_stats. In practice, rebuild after bulk loads and large deletes, not on a schedule.

Is REORGANIZE better than REBUILD?

For SQL Server light fragmentation: yes, it is always online and cheaper. Rebuild for heavy fragmentation, changing fillfactor, or switching compression.

Does rebuilding update statistics?

SQL Server rebuild does (reorganize does not). PostgreSQL REINDEX does not; run ANALYZE. Oracle REBUILD recomputes stats by default.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.