SQL Unique Constraint - Unique Key in SQL - Create Unique Constraints SQL Server



SQL UNIQUE Constraint

  • UNIQUE is like making sure everyone in a group has a different name.
  • PRIMARY KEY is like having a special leader in the group, and everyone's name must be unique, just like the UNIQUE rule.

UNIQUE Constraint on CREATE TABLE

Syntax

    CREATE TABLE tbl_Wikitechy
    (
    ID INT NOT NULL UNIQUE,
    student_Name VARCHAR(50) NOT NULL,
    Mark INT,
    Age INT
    )

Output

Step 1:

sql-create-table-unique

Step 2:

sql-create-table-unique-2

UNIQUE Constraint on ALTER TABLE

  • To establish a UNIQUE constraint on the 'ID' column after the table is already created, use the following SQL

Syntax

    ALTER TABLE tbl_Wikitechy
    ADD UNIQUE (ID);
    

Output

Step 1:

sql-alter-table-unique

Step 2:

sql-alter-table-unique-2
  • To assign a name to a UNIQUE constraint and define it on multiple columns, use the following SQLsyntax

Syntax

    ALTER TABLE tbl_Wikitechy
    ADD CONSTRAINT PK_Person UNIQUE (Id);

Output

Step 1:

sql-alter-table-constraint-output

Step 2:

sql-alter-table-constraint-output-2

DROP a UNIQUE Constraint

  • To remove a UNIQUE constraint, utilize the following SQL

Syntax

    ALTER TABLE tbl_Wikitechy
    DROP CONSTRAINT PK_Person;
    

Output

Step 1:

sql-drop-unique-ouput

Step 2:

sql-drop-unique-2

Related Searches to SQL Unique Constraint - Unique Key in SQL - Create Unique Constraints SQL Server