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 ...

Geography Data Type – SQL Server

     Geography data type in SQL Server is a useful tool for storing and manipulating geographic data. It provides a set of functions and tools for working with geographical data, such as points, lines, and polygons. In this blog, we will explore the Geography data type in SQL Server with examples. Introduction to Geography data type Geography data type is a built-in data type in SQL Server that is designed to support the storage, manipulation, and analysis of geographic data. It is based on the Open Geospatial Consortium (OGC) Simple Feature Access specification, which provides a standard way to represent geographic data in a database. The Geography data type in SQL Server stores data in a geographic coordinate system, allowing you to represent points on the surface of the earth using longitude and latitude coordinates. You can also represent lines and polygons by defining a series of points that define the shape of the line or polygon. Creating a Geography data t...

XML data type Functions – SQL Server

 The XML data type in MSSQL Server is a powerful tool for handling and manipulating XML data within a relational database system. In addition to storing XML data as a column in a table, SQL Server provides a number of XML functions and methods that allow for easy parsing, querying, and transformation of XML data. In this blog post, we will cover all XML data type methods available in MSSQL Server. value() Method: The value() method is used to extract a single value from an XML instance. This method accepts an XQuery expression as a parameter, which is used to identify the value to be extracted. The syntax of the value() method is as follows: xml . value ( XQuery expression , Data type ) For example, the following query extracts the value of the 'name' element from an XML column called 'MyXMLColumn': SELECT MyXMLColumn . value ( '(/Root/Person/Name)[1]' , 'varchar(50)' ) AS Name FROM MyTable   query() Method: The query() method i...