Contents
data/authors/Paul Logan.json

SQL Unique filtered index

The Brief

Our factory dashboard displays one key stage per factory on the initial view - a primary stage.

The stage to show is determined by a bit column in the Stages database table, which was previously updated using raw SQL by a developer - until I CRUD’ed it up.

Now, managers could update this through a web app.

A recent helpdesk ticket reported that there was a duplicate stage shown on the dashboard. A manager had ticked another stage to be primary for a factory that already had one.

How to prevent more than one primary stage per factory being updated to the database.

The Solution

I wanted to ensure that sets of stages in the table with the same FactoryID could only have one stage set to primary.

A UNIQUE INDEX with a WHERE filter predicate was the way to go:

CREATE UNIQUE INDEX [UQ_Primary_Stage_Per_Factory] ON [dbo].Stage
(
	FactoryID ASC,
	IsPrimary ASC
)
WHERE (IsPrimary=(1))
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO