sqlcmd.net validated sql reference
advanced defining MySQL MariaDB SQL Server PostgreSQL SQLite

Speed Up Queries With CREATE INDEX

Create an index on one or more columns to make lookups and joins faster.

Docker-validated Not currently validation-green

Create an index on customer_id and verify the query still returns correct results

The index is transparent to query results — the SELECT returns the same rows as it would without the index. The benefit is speed: on large tables, the database uses the index to find customer_id = 1 rows without scanning every order. Use CREATE UNIQUE INDEX to also enforce uniqueness on the indexed column.

Rows loaded before the example query runs.
Setup
CREATE TABLE orders (id INT, customer_id INT, status VARCHAR(20));

INSERT INTO
  orders (id, customer_id, status)
VALUES
  (1, 1, 'pending'),
  (2, 2, 'shipped'),
  (3, 1, 'shipped');
Shared across supported engines.
SQL
CREATE INDEX idx_orders_customer ON orders (customer_id);

SELECT
  id,
  customer_id,
  status
FROM
  orders
WHERE
  customer_id = 1
ORDER BY
  id;
Returned rows for the shared example.
idcustomer_idstatus
11pending
31shipped

Output is identical across all engines.

Where this command helps.

  • speeding up queries that filter or join on a frequently used column
  • reducing full table scans on large tables

What the command is doing.

An index is a data structure the database maintains alongside a table to allow faster row lookups by a specific column. Without an index, the database scans every row. With one, it can jump directly to matching rows. Indexes speed up WHERE filters, JOIN conditions, and ORDER BY sorts on indexed columns. The trade-off is slightly slower writes and additional storage.