SQL UNIQUE Constraint

SQL UNIQUE Constraint

SQL UNIQUE Constraint

In SQL, the UNIQUE constraint is used to ensure that the values in a column or a set of columns are unique. When we define a column or a set of columns with the UNIQUE constraint, it means that each value in that column or set of columns must be unique and cannot be duplicated.

Here is an example of how to define a column with the UNIQUE constraint:

				
					CREATE TABLE employees (
   id INT PRIMARY KEY,
   name VARCHAR(50),
   email VARCHAR(50) UNIQUE,
   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 the primary key of the table, while the “email” column has the UNIQUE constraint, which means that each email address in that column must be unique.

Here is an example of how to insert data into the “employees” table with the UNIQUE constraint:

				
					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 “email” column has the UNIQUE constraint, we must provide a unique email address in the INSERT statement. If we try to insert a row with a duplicate email address, the database will return an error.

In summary, the UNIQUE constraint is used to ensure that the values in a column or a set of columns are unique 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