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

Enforce Uniqueness With CREATE UNIQUE INDEX

Create a unique index so the database rejects duplicate values in one or more columns.

Docker-validated Not currently validation-green

Require each product SKU to appear only once

The existing SKUs are distinct, so the unique index can be created. After that, attempting to insert another row with SKU-001 would fail instead of creating an ambiguous product record.

Rows loaded before the example query runs.
Setup
CREATE TABLE products (id INT, sku VARCHAR(20), name VARCHAR(50));

INSERT INTO
  products (id, sku, name)
VALUES
  (1, 'SKU-001', 'Widget'),
  (2, 'SKU-002', 'Gadget');
Shared across supported engines.
SQL
CREATE UNIQUE INDEX ux_products_sku ON products (sku);

SELECT
  sku,
  name
FROM
  products
ORDER BY
  sku;
Returned rows for the shared example.
skuname
SKU-001Widget
SKU-002Gadget

The unique-index creation changes future write behavior, not the selected rows.

Where this command helps.

  • preventing duplicate email addresses or SKU values
  • supporting conflict handling for upsert and insert-ignore patterns

What the command is doing.

A unique index combines lookup performance with a data-integrity rule: no two rows can have the same indexed key. Use it for natural keys such as email addresses, usernames, SKU values, or external identifiers. Unlike SELECT DISTINCT, which only removes duplicates from one query result, a unique index prevents future duplicate data from being stored.