Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding named foreign key constraints in a SQL Create statement

I currently have:

CREATE TABLE  galleries_gallery (     id              INT NOT NULL PRIMARY KEY IDENTITY,     title           NVARCHAR(50) UNIQUE NOT NULL,     description     VARCHAR(256),     templateID      INT NOT NULL REFERENCES galleries_templates(id),     jsAltImgID      INT NOT NULL REFERENCES libraryImage(id)     jsAltText       NVARCHAR(500),     dateCreated     SMALLDATETIME NOT NULL,     dateUpdated     SMALLDATETIME NOT NULL,     lastUpdatedBy   INT,     deleted         BIT NOT NULL DEFAULT 0 ); 

But this adds constraints with auto generated names which make it hard to drop the constraint later. What do I need to add in order to name the constraints?

The above example is SQL Server and I also need it in PostgreSQL.

like image 675
Rumpleteaser Avatar asked Jan 24 '13 22:01

Rumpleteaser


People also ask

How can we give foreign key constraint name in SQL?

The table name (in our example, student ) is placed after the ALTER TABLE keyword. Next, the ADD FOREIGN KEY clause is followed by the name of the column that will be used as the foreign key. Then we have the REFERENCES clause with the name of the referenced table and the name of the primary key column in parentheses.

How would you add a foreign key constraint?

To create a SQL foreign key constraint, the parent table should have primary key column or column with UNIQUE constraint. In this case, table Dept is parent table which has Primary key and will be referenced in child tables having foreign key.

How do I add a foreign key constraint in SQL Server for existing table?

The syntax for creating a foreign key using an ALTER TABLE statement in SQL Server (Transact-SQL) is: ALTER TABLE child_table ADD CONSTRAINT fk_name FOREIGN KEY (child_col1, child_col2, ... child_col_n) REFERENCES parent_table (parent_col1, parent_col2, ...


1 Answers

In SQL Server, you can use the constraint keyword to define foreign keys inline and name them at the same time.

Here's the updated script:

CREATE TABLE  galleries_gallery (     id              INT NOT NULL PRIMARY KEY IDENTITY,     title           NVARCHAR(50) UNIQUE NOT NULL,     description     VARCHAR(256),     templateID      INT NOT NULL          CONSTRAINT FK_galerry_template          REFERENCES galleries_templates(id),     jsAltImgID      INT NOT NULL          CONSTRAINT FK_gallery_jsAltImg         REFERENCES libraryImage(id)     jsAltText       NVARCHAR(500),     dateCreated     SMALLDATETIME NOT NULL,     dateUpdated     SMALLDATETIME NOT NULL,     lastUpdatedBy   INT,     deleted         BIT NOT NULL DEFAULT 0 ); 

I just made a test and apparently the same thing also works in PostgreSQL: http://www.sqlfiddle.com/#!12/2ae29

like image 120
Cristian Lupascu Avatar answered Oct 01 '22 11:10

Cristian Lupascu