Smart Systems for Home

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

SQL Server Error 1505: Create Unique Index Fix

· 8 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

SQL Server error 1505 occurs when you try to create a unique index (or a unique constraint, which creates one automatically) and the statement fails because duplicate values already exist in the column or combination of columns you are indexing. The fix is to find and remove or correct those duplicates, then rerun the CREATE UNIQUE INDEX statement. You cannot force a unique index onto data that is not unique, so the work is always about cleaning the data first.

The full message usually reads something like: The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'dbo.YourTable' and the index name 'IX_YourIndex'. The duplicate key value is (…). The parenthetical value is your starting point. This guide walks through locating every duplicate, deciding what to do with them, and recreating the index safely.

What You'll Need

  • Access to SQL Server Management Studio (SSMS) or another client such as Azure Data Studio, connected with an account that can read the table and create indexes (db_owner or equivalent, or ALTER permission on the table).
  • The exact table and column list from the error message, or the columns you intended to index.
  • A maintenance window or a tested script if the table is large or heavily used, because creating an index can block writes while it runs.
  • A backup or a copy of the duplicate rows before you delete or update anything. Deleting the wrong row is not reversible without one.

Step-by-Step

  1. Read the error message carefully. Note the table name, the index name, and the duplicate key value in parentheses. If the message does not show the value, you will find it in the next step. If you are creating a unique constraint rather than an index, the message is the same; the fix is identical.
  2. Identify the exact columns involved. Run a query against the system catalog to see the key columns of the index you are trying to create, or simply use the column list from your own CREATE UNIQUE INDEX statement. For an existing index that is being rebuilt, this query shows the columns: SELECT c.name, ic.key_ordinal FROM sys.indexes i JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id WHERE i.name = 'YourIndexName' ORDER BY ic.key_ordinal; Labels and catalog views can differ slightly by SQL Server version, but these views are long-standing.
  3. Find the duplicates. Group by the key columns and count. For a single column: SELECT YourColumn, COUNT(*) AS DuplicateCount FROM dbo.YourTable GROUP BY YourColumn HAVING COUNT(*) > 1 ORDER BY DuplicateCount DESC; For multiple columns, list them all in the SELECT and GROUP BY. This returns every value that violates uniqueness. If the table is huge, add a TOP clause while you investigate.
  4. Inspect the full duplicate rows. A count tells you there is a problem; you need the whole row to decide which copy to keep. Join the duplicate list back to the table: SELECT t.* FROM dbo.YourTable t INNER JOIN (SELECT YourColumn FROM dbo.YourTable GROUP BY YourColumn HAVING COUNT(*) > 1) d ON t.YourColumn = d.YourColumn ORDER BY t.YourColumn; Look for a reliable tie-breaker such as a created date, an ID, or a status column.
  5. Decide the correction strategy. Three options cover most cases. Delete the extra rows if they are genuinely redundant. Update the duplicates to a corrected value if the data is wrong but needed. Or, if the business rule allows it, create a non-unique index instead and enforce uniqueness in the application, but only if you are certain duplicates are legitimate. For a filtered unique index, add a WHERE clause so only the rows that must be unique are included, for example WHERE IsActive = 1.
  6. Back up before changing data. Copy the affected rows into a holding table, or take a full or copy-only backup. On a production system, do this in the same maintenance window as the change so the backup reflects the state you are about to alter.
  7. Apply the fix inside a transaction. Use BEGIN TRANSACTION, run the DELETE or UPDATE, verify the row counts, then COMMIT or ROLLBACK. For example, to keep the lowest ID per duplicate group: DELETE t FROM dbo.YourTable t INNER JOIN (SELECT MIN(ID) AS KeepID, YourColumn FROM dbo.YourTable GROUP BY YourColumn HAVING COUNT(*) > 1) d ON t.YourColumn = d.YourColumn WHERE t.ID <> d.KeepID; Adjust the tie-breaker to your schema.
  8. Recheck for duplicates. Rerun the GROUP BY query from step 3. It must return zero rows before you continue. This is the step people skip, and it is why the same error comes back.
  9. Create the unique index. Run your original statement again, for example CREATE UNIQUE INDEX IX_YourIndex ON dbo.YourTable (YourColumn); For a large table, consider ONLINE = ON if your edition supports it, so writes are not blocked for the duration. If the index already exists in a broken or disabled state, drop and recreate it, or rebuild it with ALTER INDEX IX_YourIndex ON dbo.YourTable REBUILD;
  10. Verify the result. Confirm the index exists and is unique: SELECT name, is_unique, is_disabled FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.YourTable'); Then run a quick query that uses the indexed columns to confirm performance is as expected.

Common Mistakes

  • Deleting duplicates without a backup or holding table, then discovering the “extra” row was the one with the correct data.
  • Fixing only the duplicate value shown in the error message. The message reports one duplicate; there are often many more, and the index creation fails again on the next one.
  • Choosing an arbitrary row to keep. Use a deterministic tie-breaker such as the lowest or highest ID, or the most recent updated date, and document the rule.
  • Forgetting that NULLs behave differently. A standard unique index allows only one NULL per indexed column combination, so multiple NULLs will also trigger error 1505. A filtered index with WHERE YourColumn IS NOT NULL is the usual fix when NULLs are expected.
  • Running the delete on a live system during peak hours without checking blocking, causing timeouts for other users.
  • Assuming the error is a permissions problem. Error 1505 is about data uniqueness, not rights; a permissions failure produces a different message.

Tips

  • Run the duplicate-finding query as a saved script before every index deployment. It turns a production failure into a pre-check.
  • For very large tables, create the index during a low-traffic window and monitor blocking with the standard activity monitoring tools in SSMS. Index creation can take significant time and log space.
  • If duplicates are expected by design, a filtered unique index on the active subset is usually better than dropping uniqueness altogether.
  • Keep the duplicate rows you remove in a holding table for a few days. If a report or application breaks, you can restore the exact rows.
  • When the indexed columns are wide, consider a computed column that concatenates them and index that instead, but only after confirming the computed column is deterministic and precise.

Troubleshooting

The error returns after you cleaned the data. Rerun the GROUP BY query. Either new duplicates were inserted between your cleanup and the index creation, or your cleanup missed rows because of case sensitivity, trailing spaces, or collation differences. Compare values with explicit COLLATE clauses if needed.

The duplicate query returns nothing, but the index still fails. Check whether the index includes columns you did not expect, such as included columns in a unique index definition, or whether a filtered index's filter is being evaluated differently than you assumed. Also confirm you are querying the same table and schema named in the error.

The delete blocks or times out. Delete in batches, for example 1,000 rows at a time in a loop, with a short wait between batches. Check for open transactions holding locks on the table.

You cannot delete the rows because other tables reference them. Update the duplicates to a corrected value instead, or merge the child records onto the row you are keeping, then delete. Do this inside a transaction and verify foreign key relationships before committing.

The index creation itself fails on a large table. Check available disk space for the transaction log and data file, and confirm the edition supports online index operations if you requested them. If not, schedule the creation during downtime.

Frequently Asked Questions

What causes SQL Server error 1505?

Duplicate values in the column or columns you are making unique. The unique index cannot be created until every combination of key values appears only once.

Does a unique constraint produce the same error?

Yes. A UNIQUE constraint is enforced by a unique index, so duplicate data triggers the same 1505 message with the constraint's underlying index name.

Can I create the index and ignore duplicates?

No. SQL Server will not create a unique index over non-unique data. You must clean the data, use a filtered index that excludes the rows that may duplicate, or use a non-unique index instead.

Why does the error mention only one duplicate value when there are many?

The engine stops at the first violation it encounters. Fix that one and the next duplicate will be reported on the retry, which is why you should find all duplicates in one query first.

Do NULLs count as duplicates in a unique index?

Yes, for a standard unique index only one NULL is allowed per indexed column combination. If you need multiple NULLs, use a filtered unique index that excludes NULLs.

Will fixing this require downtime?

Not necessarily. The data cleanup can be done in small batches online, and the index creation can run online if your SQL Server edition supports it. On large tables, plan a low-traffic window regardless.