- SQL Basics
- SQL Introduction
- SQL Syntax
- SQL Sample Database
- SQL SELECT
- SQL WHERE
- SQL ORDER BY
- SQL DISTINCT
- SQL LIMIT
- SQL FETCH
- SQL AND
- SQL OR
- SQL BETWEEN
- SQL IN
- SQL LIKE
- SQL IS NULL
- SQL Comparison Operators
- SQL Logical Operators
- SQL Alias
- SQL CASE
- Joins and Subqueries
- SQL INNER JOIN
- SQL LEFT JOIN
- SQL RIGHT JOIN
- SQL FULL OUTER JOIN
- SQL SELF JOIN
- SQL CROSS JOIN
- SQL Subquery
- SQL Correlated Subquery
- SQL UNION
- SQL INTERSECT
- SQL EXCEPT
- Aggregate Functions
- SQL AVG
- SQL COUNT
- SQL MAX
- SQL MIN
- SQL SUM
- SQL GROUP BY
- SQL HAVING
- SQL ROLLUP
- SQL CUBE
- SQL GROUPING SETS
- Database Management
- SQL CREATE DATABASE
- SQL ALTER DATABASE
- SQL DROP DATABASE
- SQL BACKUP DATABASE
- SQL SHOW DATABASES
- SQL SELECT DATABASE
- Table Management
- SQL CREATE TABLE
- SQL ALTER TABLE
- SQL ADD COLUMN
- SQL DROP COLUMN
- SQL DROP TABLE
- SQL TRUNCATE TABLE
- SQL SHOW TABLES
- SQL RENAME TABLE
- SQL Constraints
- SQL Primary Key
- SQL Foreign Key
- SQL UNIQUE Constraint
- SQL CHECK Constraint
- SQL NOT NULL Constraint
SQL PRIMARY KEY
The PRIMARY KEY
constraint uniquely identifies each record in a table. It ensures that no duplicate or NULL values exist in the column(s) defined as the primary key.
Key Features of SQL PRIMARY KEY
- Uniquely identifies each row in a table.
- Does not allow
NULL
values. - Automatically creates an index for faster lookups.
- A table can have only one primary key.
- The primary key can be a single column or a combination of multiple columns (composite key).
SQL PRIMARY KEY Syntax
Single Column Primary Key
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
Name VARCHAR(100),
Department VARCHAR(50)
);
- The
EmployeeID
column is the primary key.
Composite Primary Key (Multiple Columns)
CREATE TABLE Orders (
OrderID INT,
ProductID INT,
Quantity INT,
PRIMARY KEY (OrderID, ProductID)
);
- The combination of
OrderID
andProductID
ensures uniqueness.
Adding a PRIMARY KEY to an Existing Table
Adding a Primary Key After Table Creation
ALTER TABLE Employees
ADD PRIMARY KEY (EmployeeID);
Removing a PRIMARY KEY
ALTER TABLE Employees
DROP PRIMARY KEY;
Summary
- A
PRIMARY KEY
uniquely identifies each record in a table. - It does not allow
NULL
or duplicate values. - Can be defined on one or multiple columns.
- Can be added or removed using
ALTER TABLE
.