how to use unique in sql code example
Example 1: set column as unique in sql server
ALTER TABLE Persons
ADD UNIQUE (ID);
Example 2: unique constraint mssql
USE AdventureWorks2012;
GO
CREATE TABLE Production.TransactionHistoryArchive4
(
TransactionID int NOT NULL,
CONSTRAINT AK_TransactionID UNIQUE(TransactionID)
);
GO
Example 3: how to select unique element in sql
DISTINCT
- select distinct * from employees; ==>
retrieves any row if it has at
least a single unique column.
- select distinct first_name from employees; ==>
retrieves unique names
from table. (removes duplicates)
- select distinct count(*) from employees;
retrieve number of unique rows
if any row has at least a single unique data.
Example 4: sql unique
This constraint ensures all values in a column are unique.
Example 1 (MySQL): Adds a unique constraint to the id column when
creating a new users table.
CREATE TABLE users (
id int NOT NULL,
name varchar(255) NOT NULL,
UNIQUE (id)
);
Example 2 (MySQL): Alters an existing column to add a UNIQUE
constraint.
ALTER TABLE users
ADD UNIQUE (id);
Example 5: unique key in sql
Unique Key:
Only unique value and also can contain NULL