Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

SQL Insert Unique Values: Step-by-Step Guide

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To insert only unique values into a SQL table, use a unique constraint or index on the column(s) that must be unique, then use an insert statement that either ignores duplicates or updates them. The simplest working approach is: add a unique index, then use INSERT ... ON CONFLICT DO NOTHING (PostgreSQL, SQLite) or INSERT IGNORE (MySQL) or MERGE (SQL Server, Oracle). This guide walks through each method with clear steps and explains what to do when duplicates still slip through.

What You'll Need

  • A SQL database (PostgreSQL, MySQL, SQLite, SQL Server, or Oracle) and a client such as psql, MySQL Workbench, SQL Server Management Studio, or a command-line tool.
  • Permission to create indexes or constraints on the target table (usually the table owner or an admin role).
  • The table already created with the columns you plan to insert into.
  • A clear idea of which column or combination of columns must be unique (for example, email address, username, or a pair like (user_id, product_id)).

Step-by-Step

  1. Identify the unique key. Decide which column(s) should never repeat. A single column like email is common; sometimes you need a composite key such as (order_id, product_id). Write down the exact column names and data types.
  2. Check for existing duplicates. Before adding a unique constraint, find rows that would violate it. Run:
    SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1;
    If duplicates exist, clean them up first (see Common Mistakes).
  3. Add a unique constraint or unique index. The syntax varies slightly by database:
    • PostgreSQL / SQLite: ALTER TABLE users ADD CONSTRAINT users_email_key UNIQUE (email); or CREATE UNIQUE INDEX idx_users_email ON users(email);
    • MySQL: ALTER TABLE users ADD UNIQUE INDEX idx_users_email (email);
    • SQL Server: ALTER TABLE users ADD CONSTRAINT UQ_users_email UNIQUE (email);
    This step is what actually enforces uniqueness. Without it, no insert method can guarantee unique values. Labels and exact syntax can differ slightly by version and edition, so check your database's documentation if a statement fails.
  4. Choose your insert strategy. Once the constraint exists, pick the method that matches your database:
    • PostgreSQL / SQLite: INSERT INTO users (email, name) VALUES ('a@example.com', 'Alice') ON CONFLICT (email) DO NOTHING; This skips the row if the email already exists. To update instead, use ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name;
    • MySQL: INSERT IGNORE INTO users (email, name) VALUES ('a@example.com', 'Alice'); This silently skips duplicate-key errors. Alternatively, INSERT ... ON DUPLICATE KEY UPDATE name = VALUES(name); updates the existing row.
    • SQL Server / Oracle: Use MERGE. Example for SQL Server:
      MERGE users AS target USING (SELECT 'a@example.com' AS email, 'Alice' AS name) AS source ON target.email = source.email WHEN NOT MATCHED THEN INSERT (email, name) VALUES (source.email, source.name);
      Oracle syntax is similar but uses MERGE INTO and may require a FROM dual subquery.
  5. Run the insert and verify. Execute the statement, then check the row count: SELECT COUNT(*) FROM users WHERE email = 'a@example.com'; It should be 1. If you used DO NOTHING or IGNORE, the statement succeeds without error even when the row is skipped.
  6. Test with a duplicate. Run the same insert again. With the unique constraint and the chosen strategy, no second row should appear. If you get an error instead, your database did not apply the duplicate-handling clause (for example, MySQL's INSERT IGNORE only ignores duplicate-key errors, not other errors like data truncation).
  7. Wrap bulk inserts in a transaction. For multiple rows, use BEGIN; ... COMMIT; (or the equivalent for your database) so a failure does not leave partial data. In PostgreSQL, ON CONFLICT DO NOTHING works per row inside a multi-row VALUES list.

Common Mistakes

  • Relying on the insert statement alone. INSERT IGNORE or ON CONFLICT only prevents duplicates if a unique constraint or index exists. Without one, duplicates will be inserted.
  • Adding a unique constraint while duplicates exist. The ALTER TABLE will fail. Find and remove duplicates first, for example by keeping the lowest id per email: DELETE FROM users a USING users b WHERE a.email = b.email AND a.id > b.id; (PostgreSQL syntax; adapt for other databases).
  • Assuming NULLs are duplicates. In most databases, multiple NULLs are allowed in a unique column because NULL is not equal to NULL. If you need to treat NULLs as equal, use a partial index or a computed column, depending on your database.
  • Using INSERT IGNORE in MySQL for non-duplicate errors. It also suppresses other errors such as invalid dates or truncated strings, which can hide real problems. Prefer ON DUPLICATE KEY UPDATE when you need precise control.
  • Forgetting case sensitivity. In MySQL, collation determines whether 'Alice@example.com' and 'alice@example.com' are considered duplicates. Check your column collation if case matters.
  • Using MERGE without a unique index on the join column. This can cause unpredictable results or errors, especially in SQL Server. Ensure the target column has a unique constraint.

Tips

  • Name your unique constraints clearly (for example, uq_users_email) so error messages are easier to interpret.
  • For bulk imports, insert into a staging table first, then use INSERT ... SELECT ... WHERE NOT EXISTS or MERGE to move only new rows into the main table.
  • Use ON CONFLICT DO UPDATE (PostgreSQL) or ON DUPLICATE KEY UPDATE (MySQL) when you want an upsert: insert if new, update if existing.
  • Test your insert strategy on a copy of the table before running it on production data.
  • Remember that unique indexes also speed up lookups on that column, so they serve two purposes.

Troubleshooting

If the insert still creates duplicates, first confirm the unique constraint exists: in PostgreSQL run \d users; in MySQL run SHOW INDEX FROM users;; in SQL Server query sys.indexes. If it is missing, add it. If the ALTER TABLE fails with a duplicate-key error, clean the data as described above. If ON CONFLICT reports a syntax error, check that your database version supports it (PostgreSQL 9.5+ and modern SQLite do; MySQL uses different syntax). If MERGE updates more rows than expected, verify the join condition and that the source has no duplicate keys. If you get a permission error when creating the index, ask your database administrator to grant the necessary rights. Finally, if the statement succeeds but the row count does not change, that is expected behavior for DO NOTHING and IGNORE; it means the duplicate was skipped correctly.

Frequently Asked Questions

Can I insert unique values without a unique constraint?

Not reliably. You can use INSERT ... SELECT ... WHERE NOT EXISTS to avoid inserting a row that already exists, but without a unique constraint two concurrent sessions can still insert the same value. A unique index is the only way to guarantee uniqueness at the database level.

What is the difference between INSERT IGNORE and ON DUPLICATE KEY UPDATE?

INSERT IGNORE skips the row when a duplicate key is found and also suppresses some other errors. ON DUPLICATE KEY UPDATE updates the existing row with new values instead of skipping it. Use the first when you want to keep the old data, the second when you want to refresh it.

Does ON CONFLICT work in MySQL?

No. MySQL uses INSERT IGNORE or ON DUPLICATE KEY UPDATE. PostgreSQL and SQLite use ON CONFLICT. SQL Server and Oracle use MERGE.

How do I handle multiple columns that must be unique together?

Create a composite unique constraint: ALTER TABLE orders ADD CONSTRAINT uq_order_product UNIQUE (order_id, product_id); Then use the same insert strategy, listing both columns in the conflict target for PostgreSQL: ON CONFLICT (order_id, product_id) DO NOTHING.

Will a unique index slow down inserts?

Yes, slightly, because the database must check the index on every insert. The trade-off is worth it for data integrity and faster lookups. For very high-volume inserts, consider batching and testing performance.

Can I add a unique constraint to an existing table with data?

Yes, but only after removing duplicates. The ALTER TABLE statement will fail if any duplicate values exist. Clean the data first, then add the constraint.