Keys in SQL Server | YourSite

Keys in SQL Server

SQL SERVER 978 views

Example:

Code: Primary Key




-- All Key Examples 

-- Example: Primary Key

CREATE TABLE SAMPLE_TABLE1 (
	COL1 integer,
	COL2 nvarchar(30),
	COL3 nvarchar(50),
	PRIMARY KEY (COL1)
);


<h4> Code: Insert Data </h4>
<pre class="prettyprint">
<xmp>

INSERT INTO SAMPLE_TABLE1 VALUES
(1, 'text', 'abc'),
(2, 'text', 'abc')


INSERT INTO SAMPLE_TABLE1 VALUES
(1, 'text', 'abc')
 -- This is not possible for primary key (The duplicate key value is (1))

Code: Composite Key



-- Composite Key

CREATE TABLE SAMPLE_TABLE (
	COL1 integer,
	COL2 nvarchar(30),
	COL3 nvarchar(50),
	PRIMARY KEY (COL1, COL2)
);

INSERT INTO SAMPLE_TABLE VALUES
(1, 'text', 'abc'),
(1, 'text1', 'abc')

INSERT INTO SAMPLE_TABLE VALUES
(1, 'text', 'abc')
 -- this can't be inserted (The duplicate key value is (1, text))


SELECT * FROM SAMPLE_TABLE

Code: Unique Key



-- Unique key 

CREATE TABLE SAMPLE_TABLE3 (
    COL1 int NOT NULL UNIQUE,
    COL2 varchar(255) NOT NULL,
    COL3 varchar(255), 
);

INSERT INTO SAMPLE_TABLE3 VALUES
(1, 'text', 'abc'),
(2, 'text1', 'abc')

INSERT INTO SAMPLE_TABLE3 VALUES
(1, 'text', 'abc')
-- This is not possible (The duplicate key value is (1))


-- Point 1: Can be more than one unique key in one table
CREATE TABLE SAMPLE_TABLE4 (
    COL1 int UNIQUE,
    COL2 varchar(255) UNIQUE,
    COL3 varchar(255) UNIQUE
);

INSERT INTO SAMPLE_TABLE4 VALUES
(1, 'text', 'abc'),
(2, 'text1', 'abc2')

INSERT INTO SAMPLE_TABLE4 VALUES
(3, 'text3', 'abc') -- Not Possible (The duplicate key value is (abc))
(3, 'text', 'abc3') -- Not Possible (The duplicate key value is (text))
(1, 'text3', 'abc3') -- Not possible (The duplicate key value is (1))

SELECT * FROM SAMPLE_TABLE4
-- Point 2: Unique key can have NULL values
INSERT INTO SAMPLE_TABLE4 VALUES
(NULL, NULL, NULL)


🚀 More Blogs You Might Like

Explore more articles and keep learning

What is Bounce Rate in SEO? Complete Guide for Beginners
search-engine-optimization
What is Bounce Rate in SEO? Complete Guide for Beginners

Learn what bounce rate is in SEO, how it is calculated, why it matters, common causes of high bounce rates, an...

👁 28 2026-05-24
Read More →
Comprehensive Interviewer Guide - Detailed Article
skill
Comprehensive Interviewer Guide - Detailed Article

Learn how to conduct effective interviews with this comprehensive interviewer guide. Explore hiring strategies...

👁 43 2026-05-22
Read More →
Five Industry Shifts Reshaping the AI Ecosystem (2026 Trends)
skill
Five Industry Shifts Reshaping the AI Ecosystem (2026 Trends)

Five Industry Shifts Reshaping the AI Ecosystem (2026 Trends)...

👁 38 2026-05-19
Read More →
How to Grow Your Business Mindset Step by Step
skill
How to Grow Your Business Mindset Step by Step

Learn how to develop and grow a successful business mindset step by step. Discover entrepreneurial thinking, p...

👁 56 2026-05-09
Read More →