How to limit maximum number of rows in a table to just 1
These two constraints would do:
CREATE TABLE dbo.Configuration ( ConfigurationID TINYINT NOT NULL DEFAULT 1, -- the rest of the columns CONSTRAINT Configuration_PK PRIMARY KEY (ConfigurationID), CONSTRAINT Configuration_OnlyOneRow CHECK (ConfigurationID = 1) ) ;
You need both the
PRIMARY KEY (or a
UNIQUE constraint) so no two rows have the same
ID value, and the
CHECK constraint so all rows have the same
ID value (arbitrarily chosen to
In combination, the two almost opposite constraints restrict the number of rows to either zero or one.
On a fictional DBMS (no current SQL implementation allows this construction) that allows a primary key consisting of 0 columns, this would be a solution, too:
CREATE TABLE dbo.Configuration ( -- no ConfigurationID needed at all -- the rest of the columns CONSTRAINT Configuration_PK PRIMARY KEY () -- 0 columns! ) ;
You could define the ID as a computed column evaluating to a constant value, and declare that column to be unique:
CREATE TABLE dbo.Configuration ( ID AS CAST(1 AS tinyint), -- or: AS bit ... -- other columns CONSTRAINT UQ_Configuration_ID UNIQUE (ID) );
You can also use trigger..
create trigger LimitTable on YourTableToLimit after insert as declare @tableCount int select @tableCount = Count(*) from YourTableToLimit if @tableCount > 50 begin rollback end go