Unique Constraint

SQL unique constraint is a type of constraint that ensures that the data in a column or set of columns is unique across all rows in a table. It is used to prevent duplicate values from being inserted into a table and to ensure data integrity.

To create a unique constraint in SQL, you can use the UNIQUE keyword in the CREATE TABLE statement. For example, if you want to create a unique constraint on the email column in a users table, you can use the following SQL statement:

CREATE TABLE users (
  id INT PRIMARY KEY,
  name VARCHAR(50),
  email VARCHAR(50) UNIQUE,
  age INT
);

In this example, the email column has been defined as unique. This means that every value in this column must be unique across all rows in the users table. If you try to insert a row with a duplicate value in the email column, the database will throw an error.

You can also add a unique constraint to an existing table using the ALTER TABLE statement. For example, if you want to add a unique constraint to the username column in an existing users table, you can use the following SQL statement:

ALTER TABLE users
ADD CONSTRAINT unique_username UNIQUE (username);

In this example, the unique_username constraint has been added to the username column. This means that every value in the username column must be unique across all rows in the users table.

Unique constraints are important for maintaining data integrity and preventing data inconsistencies. By using unique constraints, you can ensure that your database contains only unique values, which can help you avoid data quality issues and improve the accuracy of your data.