// dialect comparison

CREATE INDEX in every SQL dialect

The bread-and-butter index statement: nearly identical everywhere, with a few differences in naming and locking.

Filed under インデックス

The verdict

This is one of the most portable statements in SQL: identical syntax in all five engines. The real differences hide in concurrency options, which every engine spells differently.

Where they differ

Every engine builds a B-tree index with the same core statement. The differences are around what happens to concurrent writers while the index is being built.

How each engine writes it

SQL Server

CREATE INDEX idx_orders_customer_id ON orders (customer_id);

An offline build holds a shared lock: readers continue, writers wait. WITH (ONLINE = ON) keeps writes flowing (Enterprise and Enterprise Developer editions, Azure SQL; not Standard).

PostgreSQL

CREATE INDEX idx_orders_customer_id ON orders (customer_id);

Defaults to B-tree. CREATE INDEX CONCURRENTLY avoids blocking writes but cannot run inside a transaction.

MySQL

CREATE INDEX idx_orders_customer_id ON orders (customer_id);

InnoDB builds B-tree indexes; InnoDB Online DDL allows concurrent reads and usually writes while it builds.

SQLite

CREATE INDEX idx_orders_customer_id ON orders (customer_id);

Only B-tree indexes exist. The database is locked to other writers while the index builds.

Oracle

CREATE INDEX idx_orders_customer_id ON orders (customer_id);

B-tree by default. Without ONLINE, DML on the table waits for the build; CREATE INDEX ... ONLINE (Enterprise Edition) keeps it writable.

Questions that come up

Do I need an index on every column I filter?

No. Indexes slow down writes and take space. Index columns that appear in frequent WHERE, JOIN and ORDER BY clauses where the query currently scans too many rows.

Does the index update itself?

Yes. Every engine maintains the index automatically on INSERT, UPDATE and DELETE. REBUILD or REINDEX is only needed for bloat or corruption.

Is a primary key automatically indexed?

Yes, every engine backs a primary key with an index. InnoDB and SQL Server (by default) go further and store the table itself in primary-key order, as do SQLite tables keyed by INTEGER PRIMARY KEY and Oracle index-organized tables. Ordinary PostgreSQL and Oracle tables are heaps with a separate key index.

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.