Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

PRIMARY KEY



SQL PRIMARY KEY Constraint


In SQL, the PRIMARY KEY constraint is used to uniquely identify each record (row) in a table. It ensures that every value in the specified column or combination of columns is unique and not null. Additionally, a table can have only one PRIMARY KEY constraint.

Here's how you can define a PRIMARY KEY constraint when creating a table:


            CREATE TABLE table_name (
                column1 datatype PRIMARY KEY,
                column2 datatype,
                ...
            );
        

In this syntax:

Example:

Let's say we have a table named employees and we want to ensure that the employee_id column uniquely identifies each employee:


            CREATE TABLE employees (
                employee_id INT PRIMARY KEY,
                first_name VARCHAR(50),
                last_name VARCHAR(50),
                ...
            );
        

In this example, the employee_id column is defined as the primary key. This means that each employee_id value must be unique within the employees table, and it cannot contain NULL values.

If you try to insert a row with a duplicate employee_id, or if you try to insert a row with a NULL value in the employee_id column, you will receive an error due to the PRIMARY KEY constraint violation.

You can also define a composite primary key, which consists of multiple columns. For example:


            CREATE TABLE orders (
                order_id INT,
                product_id INT,
                PRIMARY KEY (order_id, product_id)
            );
        

In this example, the combination of order_id and product_id forms a composite primary key for the orders table. This means that each combination of order_id and product_id must be unique within the orders table.

Using the PRIMARY KEY constraint ensures data integrity by preventing duplicate or null values in the designated key columns. It also facilitates efficient indexing and retrieval of data.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java