SQL PRIMARY KEY Constraint

SQL PRIMARY KEY Constraint

SQL PRIMARY KEY Constraint

In SQL, the PRIMARY KEY constraint is used to define a column or a set of columns as the primary key of a table. A primary key is a unique identifier for each row in a table and is used to ensure that the table has no duplicate rows.

Here is an example of how to define a primary key in SQL:

				
					CREATE TABLE employees (
   id INT PRIMARY KEY,
   name VARCHAR(50),
   email VARCHAR(50),
   phone VARCHAR(20)
); 

				
			

In this example, we have defined a table called “employees” with four columns: “id”, “name”, “email”, and “phone”. The “id” column is defined as the primary key of the table using the PRIMARY KEY constraint.

Here is an example of how to insert data into the “employees” table with a primary key:

				
					INSERT INTO employees (id, name, email, phone)
VALUES (1, 'John Doe', 'johndoe@email.com', '123-456-7890'); 

				
			

In this example, we are inserting a new row into the “employees” table with values for the “id”, “name”, “email”, and “phone” columns. Since the “id” column is the primary key of the table, we must provide a unique value for that column in the INSERT statement. If we try to insert a row with a duplicate value in the “id” column, the database will return an error.

In summary, the PRIMARY KEY constraint is used to define a column or a set of columns as the primary key of a table in SQL. It is essential for maintaining data integrity and ensuring the accuracy and consistency of data in a database.

Join To Get Our Newsletter
Spread the love