📜  SQL unique-key(1)

📅  最后修改于: 2023-12-03 15:20:15.865000             🧑  作者: Mango

SQL Unique Key

In SQL, a unique key is a constraint that is used to ensure that the values in a column or a group of columns are unique.

Syntax

To create a unique key constraint, you use the following syntax:

ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE(column1, column2, ... column_n);

In this syntax, table_name is the name of the table that you want to add the constraint to, constraint_name is the name of the constraint, and column1, column2, and column_n are one or more columns that you want to enforce uniqueness on.

Example

Let's create a simple users table with a unique key constraint on the username column:

CREATE TABLE users (
  id INT PRIMARY KEY,
  username VARCHAR(50) NOT NULL,
  email VARCHAR(50) NOT NULL,
  CONSTRAINT unique_username UNIQUE(username)
);

In this example, we're creating a users table with three columns: id, username, and email. The id column is the primary key, and the username and email columns are required and cannot be empty. We're also adding a unique key constraint on the username column to ensure that every username in the table is unique.

Conclusion

SQL unique key constraints are an important tool that can be used to ensure the integrity of your database. By enforcing uniqueness on a column or group of columns, you can prevent duplicate data and maintain data consistency.