Database naming conventions for SQL Server tables and keys

Database naming conventions are the rules for naming tables, columns, keys and constraints. A set for SQL Server, and what breaks when SQL Server picks names.

What database naming conventions cover

Database naming conventions are the rules a team follows when it names tables, columns, keys, constraints and indexes, so that anyone can guess a name before looking it up. In a schema that follows them, MenuItemId is a menu item’s key in every table that holds one, and FK_OrderItem_MenuItem_MenuItemId can only be the foreign key from order items to menu items.

The examples come from a restaurant: dining tables, the orders taken at them, the menu, and the items on each order, four tables of the restaurant management system template. Most of the rules below pick one of two good options, and keeping the choice matters more than which one you pick. The rules for constraints are different: there, one option breaks deployments.

Singular or plural table names?

Singular. A table’s name says what one row is: a row of dbo.MenuItem is one menu item, and its key is MenuItemId. With a plural table the key is still MenuItemId, so the table and its key differ by a letter, and sooner or later someone writes MenuItemsId. English plurals don’t follow one rule either: Category becomes Categories, Staff stays Staff, Person becomes People. A table that links two others reads better singular too: OrderItem is an item on an order, where plurals give OrderItems or OrdersItems.

The case for plurals is that a table holds many rows, and that some nouns are reserved words. Order is one: CREATE TABLE dbo.Order fails with Msg 156, “Incorrect syntax near the keyword ‘Order’.” Brackets get it through, dbo.[Order], and then every query needs them. The template calls its orders TableOrder instead, a name that also says which kind of order it is. Check new names against Microsoft’s reserved keywords list.

Most SQL table naming conventions agree on the rest: whole words (Quantity, not Qty), only letters, digits and _ so no name needs brackets, and no tbl prefix. The catalog already knows a table is a table.

PascalCase or snake_case?

In SQL Server, case is for the reader. Names compare by the database’s collation, and a US English install’s default collation, SQL_Latin1_General_CP1_CI_AS, ignores case: dbo.menuitem finds dbo.MenuItem, and creating dbo.menuitem beside it fails with Msg 2714, “There is already an object named ‘menuitem’ in the database.” PascalCase is common on SQL Server, and Microsoft’s own examples use it (Sales.SalesOrderHeader).

PostgreSQL is where the choice bites: unquoted names are folded to lower case, so MenuItem becomes menuitem unless every query quotes it. A schema that has to run there as well takes snake_case: menu_item, menu_item_id. Either works. A mix, dbo.MenuItem with a menu_category_id, is the one wrong answer.

A schema is the first part of every name. dbo is the default; a larger database groups tables by area, floor.DiningTable and menu.MenuItem. Keep the table’s full name inside its schema, menu.MenuItem rather than menu.Item, because the key columns are named after the table: an ItemId in an order wouldn’t say which item.

How to name key and foreign key columns

A key column is the table’s name followed by Id: DiningTableId, TableOrderId, MenuItemId. A foreign key column takes the name of the column it references, so an order holds DiningTableId and an order item holds TableOrderId and MenuItemId. A join then pairs each name with itself, oi.MenuItemId = mi.MenuItemId. Here are the four tables, with every constraint left for SQL Server to name, as many scripts leave them:

CREATE TABLE dbo.DiningTable (
  DiningTableId int        IDENTITY PRIMARY KEY,
  TableNumber   varchar(5) NOT NULL UNIQUE,
  Seats         tinyint    NOT NULL CHECK (Seats > 0)
);
CREATE TABLE dbo.TableOrder (
  TableOrderId  int          IDENTITY PRIMARY KEY,
  DiningTableId int          NOT NULL
    REFERENCES dbo.DiningTable (DiningTableId),
  OpenedAt      datetime2(0) NOT NULL DEFAULT SYSDATETIME()
);
CREATE TABLE dbo.MenuItem (
  MenuItemId int           IDENTITY PRIMARY KEY,
  Name       nvarchar(100) NOT NULL UNIQUE,
  Price      decimal(8, 2) NOT NULL CHECK (Price >= 0)
);
CREATE TABLE dbo.OrderItem (
  TableOrderId int     NOT NULL
    REFERENCES dbo.TableOrder (TableOrderId),
  MenuItemId   int     NOT NULL
    REFERENCES dbo.MenuItem (MenuItemId),
  Quantity     tinyint NOT NULL DEFAULT 1,
  PRIMARY KEY (TableOrderId, MenuItemId)
);
dbo.DiningTable with alternate key TableNumber; dbo.TableOrder with foreign key DiningTableId; dbo.MenuItem with alternate key Name; dbo.OrderItem whose primary key TableOrderId and MenuItemId are also its foreign keys; a dashed line from DiningTable to TableOrder, solid lines from TableOrder and MenuItem to OrderItem.
Every key column is {Table}Id, every foreign key column has the name of the key it holds. The script names none of its constraints; drawn here, each takes the name its naming template gives it.

Id in every table is the other common choice; Id or CustomerId weighs the two. Either way, two cases need a different name: a second foreign key to the same table, and a table that points at itself, such as members who mentor other members. There the column gets a role name, MentorId, as the post on the unary relationship shows.

What SQL Server names a constraint you don’t name

The script declares 13 constraints and names none of them. SQL Server names them itself, and the name appears in any error message about a constraint violation. A dish entered twice shows one:

INSERT INTO dbo.MenuItem (Name, Price)
VALUES (N'Margherita', 11.50), (N'Caesar salad', 9.00);
INSERT INTO dbo.MenuItem (Name, Price)
VALUES (N'Margherita', 12.00);
Msg 2627, Level 14, State 1, Line 3
Violation of UNIQUE KEY constraint 'UQ__MenuItem__737584F684C6BD20'. Cannot insert duplicate key in object 'dbo.MenuItem'. The duplicate key value is (Margherita).
The statement has been terminated.

UQ__MenuItem__737584F684C6BD20 is the unique constraint on Name. Build a second database from the same script, as a test server or production would be built, and the same insert fails on a different name:

Msg 2627, Level 14, State 1, Line 3
Violation of UNIQUE KEY constraint 'UQ__MenuItem__737584F6AE1A2A75'. Cannot insert duplicate key in object 'dbo.MenuItem'. The duplicate key value is (Margherita).
The statement has been terminated.

The name ends in a hex suffix that can’t be known in advance. A primary or unique key’s differs between two databases built from the same script, and the others change with what a database held before the script ran.

Now the restaurant adds a lunch Margherita beside the dinner one, so Name can’t stay unique. The migration is written on the first database and drops the constraint by the name it has there:

ALTER TABLE dbo.MenuItem
  DROP CONSTRAINT UQ__MenuItem__737584F684C6BD20;
dbo.DiningTable, dbo.TableOrder, dbo.MenuItem and dbo.OrderItem after the migration: MenuItem still has alternate key Name; a dashed line from DiningTable to TableOrder, solid lines from TableOrder and MenuItem to OrderItem.
The script names a constraint these tables don't have, so nothing is dropped: Name keeps its AK, as it does in the second database.

It runs in the first database. In the second:

Msg 3728, Level 16, State 1, Line 1
'UQ__MenuItem__737584F684C6BD20' is not a constraint.
Msg 3727, Level 16, State 1, Line 1
Could not drop constraint. See previous errors.

A schema comparison of the two databases finds one constraint under two names. Defaults are no better: dropping TableOrder.OpenedAt fails with Msg 5074, “The object ‘DF__TableOrde__Opene__4F7CD00D’ is dependent on column ‘OpenedAt’”, so the script has to drop the default first, by a name it can’t know in advance.

How to name constraints and indexes

Name every constraint in the script, built from its table and its columns:

  • PK_{Table}: PK_MenuItem. A table has one primary key, so its name is enough.
  • FK_{Table}_{ParentTable}_{Columns}: FK_OrderItem_MenuItem_MenuItemId, the child, the parent, then the columns.
  • AK_{Table}_{Columns}: AK_MenuItem_Name, for an alternate key. UQ_ is the other common prefix; pick one.
  • DF_{Table}_{Column}: DF_TableOrder_OpenedAt.
  • CK_{Table}_{Columns}: CK_MenuItem_Price.
  • IX_{Table}_{Columns}: IX_OrderItem_MenuItemId.

The table goes into every name because constraint names are unique in their schema: DF_Quantity would be free for one table only. An index is always named in the script, since CREATE INDEX without a name fails with Msg 156, and SQL Server doesn’t index a foreign key column for you, so each one is written out:

CREATE TABLE dbo.DiningTable (
  DiningTableId int        IDENTITY
    CONSTRAINT PK_DiningTable PRIMARY KEY,
  TableNumber   varchar(5) NOT NULL
    CONSTRAINT AK_DiningTable_TableNumber UNIQUE,
  Seats         tinyint    NOT NULL
    CONSTRAINT CK_DiningTable_Seats CHECK (Seats > 0)
);
CREATE TABLE dbo.TableOrder (
  TableOrderId  int          IDENTITY
    CONSTRAINT PK_TableOrder PRIMARY KEY,
  DiningTableId int          NOT NULL
    CONSTRAINT FK_TableOrder_DiningTable_DiningTableId
    REFERENCES dbo.DiningTable (DiningTableId),
  OpenedAt      datetime2(0) NOT NULL
    CONSTRAINT DF_TableOrder_OpenedAt DEFAULT SYSDATETIME()
);
CREATE INDEX IX_TableOrder_DiningTableId
  ON dbo.TableOrder (DiningTableId);
CREATE TABLE dbo.MenuItem (
  MenuItemId int           IDENTITY
    CONSTRAINT PK_MenuItem PRIMARY KEY,
  Name       nvarchar(100) NOT NULL
    CONSTRAINT AK_MenuItem_Name UNIQUE,
  Price      decimal(8, 2) NOT NULL
    CONSTRAINT CK_MenuItem_Price CHECK (Price >= 0)
);
CREATE TABLE dbo.OrderItem (
  TableOrderId int     NOT NULL,
  MenuItemId   int     NOT NULL,
  Quantity     tinyint NOT NULL
    CONSTRAINT DF_OrderItem_Quantity DEFAULT 1,
  CONSTRAINT PK_OrderItem
    PRIMARY KEY (TableOrderId, MenuItemId),
  CONSTRAINT FK_OrderItem_TableOrder_TableOrderId
    FOREIGN KEY (TableOrderId)
    REFERENCES dbo.TableOrder (TableOrderId),
  CONSTRAINT FK_OrderItem_MenuItem_MenuItemId
    FOREIGN KEY (MenuItemId)
    REFERENCES dbo.MenuItem (MenuItemId)
);
CREATE INDEX IX_OrderItem_MenuItemId
  ON dbo.OrderItem (MenuItemId);
dbo.DiningTable with alternate key TableNumber; dbo.TableOrder with foreign key DiningTableId; dbo.MenuItem with alternate key Name; dbo.OrderItem whose primary key TableOrderId and MenuItemId are also its foreign keys; the same lines as before.
The same tables with every constraint named in the script. The defaults, checks and indexes aren't drawn; their names are in the script.

The duplicate dish now fails on AK_MenuItem_Name in both databases, and a migration that drops AK_MenuItem_Name runs in both.

Look at the names in that script. Each of the 15 follows from its table and columns, which is why typing them by hand doesn’t hold up. One person writes FK_OrderItem_MenuItem, another FK_OrderItems_MenuItemId. A renamed table keeps every name built from the old one: after sp_rename turns dbo.TableOrder into dbo.GuestOrder, its primary key, two foreign keys, its default and its index all still say TableOrder. A database naming convention only holds when the names are generated from it, by whatever writes the script, and checked each time the schema changes.

How ERDsmith helps

Constraint names are made from the table and its columns, so in ERDsmith they are written for you as you design, and a convention changed later reaches every name at once:

  • Keys, foreign keys, indexes, defaults and checks are named by the project’s naming templates, PK_{Table}, FK_{Table}_{ParentTable}_{Columns}, DF_{Table}_{Column} and the rest; the default set is the one above.
  • No constraint stays unnamed: a blank or missing name goes back to its template, so every name is known before the first deployment.
  • A foreign key column is named by its own template, {ParentColumn} by default, so dbo.OrderItem gets MenuItemId; a role name replaces it where you set one.
  • A name follows its template until you type a different one. Rename dbo.TableOrder and every constraint and index name built from {Table} or {ParentTable} changes with it.
  • A template changed in the project settings renames every name that follows it in one step, and keeps the names you set by hand.