How to set unique constraints when creating a table in SQL?

In SQL, you can use the UNIQUE keyword to set a unique constraint. This constraint ensures that the values in a column or a few columns in a table are unique, meaning that these column values cannot be duplicated in the entire table. When creating a table, you can use the UNIQUE keyword at the end of the column definition to set a unique constraint. For example, when creating a table named “users” with a column named “username,” you can use the following syntax to set a unique constraint:

CREATE TABLE users (

    id INT PRIMARY KEY,

    username VARCHAR(255) UNIQUE,

    ...

);

In the above example, the “username” column is set as a unique constraint, which means that the values in the “username” column of any two rows in the table cannot be the same. When trying to insert or update data, if the unique constraint is violated, the database will throw an error. If you want to set a unique constraint for multiple columns, you can use multi-column unique constraints. For example, when creating a table named “users” with columns “username” and “email”, you can use the following syntax to set a multi-column unique constraint:

CREATE TABLE users (

    id INT PRIMARY KEY,

    username VARCHAR(255),

    email VARCHAR(255),

    UNIQUE (username, email),

    ...

);

In the example above, the columns “username” and “email” have been set as a unique constraint, which means that the combination of values in these two columns for any two rows in the table cannot be the same. If an attempt is made to insert or update data that violates this unique constraint, the database will throw an error.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds