Skip to main content

Primary Key, Foreign Key Column and Check Constraint - SQL Server

Ø  What is Primary Key?

              A primary key is a unique identifier for a record or row in a database table. It is a column or set of columns that uniquely identifies each record in a table and serves as a reference point for other tables that need to link to that table's records. Primary keys are used to enforce the integrity of the database by ensuring that each record can be uniquely identified, and they also help to optimize database performance by providing a fast way to retrieve data.

To create a primary key in SQL Server, you can use the CREATE TABLE statement with the PRIMARY KEY constraint. Here's an example:

     CREATE TABLE Customers (

    CustomerID int PRIMARY KEY,

    FirstName varchar(50),

    LastName varchar(50),

    Email varchar(50)

);

In this example, we're creating a table called Customers with four columns. The CustomerID column is declared as an int and is designated as the primary key using the PRIMARY KEY constraint. The FirstName, LastName, and Email columns are declared as varchar data types.

Note that you can also create a primary key using the ALTER TABLE statement. For example:

             ALTER TABLE Customers

ADD CONSTRAINT PK_Customers PRIMARY KEY (CustomerID);

 This statement adds a primary key constraint to an existing Customers table, using the ADD CONSTRAINT clause and the PRIMARY KEY keyword. The CustomerID column is specified as the primary key column.

 Ø  What is Foreign Key?           

A foreign key is a column or set of columns in a table that refers to the primary key of another table. It is used to establish a relationship between two tables in a relational database. The purpose of a foreign key is to ensure referential integrity, which means that the data in the related tables remains consistent and accurate.

When a table has a foreign key, it is creating a reference to another table's primary key. This creates a link between the two tables, allowing data to be shared and used in different ways. For example, if you have a table of orders and a table of customers, you could use a foreign key in the orders table to reference the customer ID in the customers table. This would allow you to see which customer placed each order, and to link customer information to the orders as needed.

To add a foreign key in SQL Server, you can use the ALTER TABLE statement with the ADD CONSTRAINT clause. Here's an example:

ALTER TABLE Orders

ADD CONSTRAINT FK_Orders_Customers

FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID);

In this example, we're adding a foreign key constraint to the Orders table, using the ADD CONSTRAINT clause and the FOREIGN KEY keyword. The CustomerID column in the Orders table is specified as the foreign key column, and the Customers table is specified as the referenced table, with its CustomerID column as the referenced column.

Note that you can also specify additional options for the foreign key constraint, such as ON DELETE and ON UPDATE actions. For example:

ALTER TABLE Orders

ADD CONSTRAINT FK_Orders_Customers

FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)

ON DELETE CASCADE

ON UPDATE CASCADE;

 

In this example, we're adding ON DELETE CASCADE and ON UPDATE CASCADE options to the foreign key constraint. This means that if a customer is deleted or updated, all related orders will also be deleted or updated automatically.

Ø  Check Constraints

A check constraint in SQL Server is used to ensure that the data entered into a column or a set of columns meets a certain condition. It can be used to restrict the range of values that can be entered into a column or to validate data against a specific pattern or formula. Check constraints can be applied to a single column or to multiple columns within a table.

Here's an example of creating a check constraint:

CREATE TABLE Employees

(

    EmployeeID int PRIMARY KEY,

    FirstName varchar(50),

    LastName varchar(50),

    Age int,

    CONSTRAINT CHK_Employees_Age CHECK (Age >= 18 AND Age <= 65)

)

 In this example, we're creating a table called Employees with four columns: EmployeeID, FirstName, LastName, and Age. We've also added a check constraint to the table to ensure that the Age column contains values between 18 and 65.

Once the check constraint is in place, any attempt to insert or update data in the Age column that falls outside the specified range will be rejected with an error message. For example:

INSERT INTO Employees (EmployeeID, FirstName, LastName, Age) VALUES (1, 'John', 'Doe', 16);

 This statement will fail with the following error message:

The INSERT statement conflicted with the CHECK constraint "CHK_Employees_Age". The conflict occurred in database "MyDatabase", table "dbo.Employees", column 'Age'.

Note that you can also use check constraints to validate data against other columns within the same table or to perform more complex validations using user-defined functions.

Comments

Popular posts from this blog

SFTP Integration in SSIS package Using WinSCP DLL

  In this blog, I am planning to write about SSIS SFTP Task details and reference sites, upload and download the files from SFTP server using SSIS package with help of the winscp library. Steps to configure the winscp DLL and Download Files 1.        Please download the DLL and required files from below path https://winscp.net/eng/downloads.php#additional 2.        Once Downloaded, use the below comments to add in Local GAC "Path to the gacutil exe \gacutil.exe" /i WinSCPnet.dll 3.        Please use the below URL as guide to implement the SSIS script task to download the files from SFTP using winscp as library https://winscp.net/eng/docs/library_ssis 4.        I am just briefing the steps based on the above URL what we can try in SSIS package. 5.        Please create the below variables in SSIS package which we need ...

SQL Server - Tables

  What is Table?               Tables are database objects that contain all the data in a database. In tables, data is logically organized in a row-and-column format similar to a spreadsheet. Each row represents a unique record, and each column represents a field in the record.               There are different types of table available in SQL Server 1.        Partitioned Tables 2.        Temporal tables 3.        Wide Tables 4.        System Tables Please refer the below link to more about the Tables. https://learn.microsoft.com/en-us/sql/relational-databases/tables/tables?view=sql-server-ver16   Create a table in SQL Server There are multiple ways to create a table in SQL server. 1.    ...

SQL Server - Data Types

Data Types  In this post I have collected the information from micro soft site and keep all the same in a single page.  Please find the details    Data types are the heart of the SQL language, as developer or designer we need to see the every data as data type, how we can store the data in the database. In SQL Server, each column, local variable, expression, and parameter has a related data type. A data type is an attribute that specifies the type of data that the object can hold: integer data, character data, monetary data, date and time data, binary strings, and so on. In SQL Server, based on the characteristic data types grouped as below categories Exact Numerics Unicode character strings   Approximate Numerics Binary strings Date and time Other data types Character strings   ...