Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good idea to specify schema as part of constraint name?

Tags:

sql

sql-server

In my SQL Server databases I group my tables by schema to help organize their purpose.

When I create constraints for columns on these tables I've been including the Schema as part of the name. For example, if I have a tables such as Com.WebUser and Com.Company:

PK_Com_WebUser                     --Primary key constraint
FK_Com_WebUser_Com_Company         --Foreign key to Com.Company table
UQ_Com_WebUser_CompanyID_Username  --Unique constraint on CompanyID & Username

I figured in the case I ever had another table with the same name in a different schema putting the schema in the constraint name would make things clearer, but the names are a bit verbose.

Is there a best practice for naming these objects?

like image 204
C.J. Avatar asked Feb 09 '12 21:02

C.J.


2 Answers

I think adding the schema name is a good practice for the reason you already mentioned (repeated table names across schemas), I wouldn't worry about how verbose the constraint name is, because you rarely need to reference those constraints.

like image 141
Bassam Mehanni Avatar answered Sep 22 '22 03:09

Bassam Mehanni


Technically the constraint belongs to the same schema as it's base table. You also cannot reference the constraint without specifying the table as well. You can see that in the following code snippet:

CREATE SCHEMA s1;
GO
CREATE SCHEMA s2;
GO
CREATE TABLE s1.T(i int CONSTRAINT tpk PRIMARY KEY);
GO
CREATE TABLE s2.T(i int CONSTRAINT tpk PRIMARY KEY);
GO
SELECT OBJECT_SCHEMA_NAME(object_id) SchemaName,name,type_desc FROM sys.objects WHERE schema_id IN (SCHEMA_ID('s1'),SCHEMA_ID('s2'));
GO

The only exception is the OBJECT_ID function. In there you can reference a constraint without specifying it's base table. But when using this function you should always specify the schema as well anyway:

SELECT OBJECT_ID('s1.tpk'),OBJECT_ID('s2.tpk');

Because of all the above I consider putting the schema name into the contraint name superfluous repetition. So, adhering to the DRY principle, you should not do it.

like image 45
Sebastian Meine Avatar answered Sep 25 '22 03:09

Sebastian Meine