0% found this document useful (0 votes)
8 views

SQL Comments (1)

SQL commands are categorized into five types: DDL for defining database structures, DQL for querying data, DML for manipulating data, DCL for controlling access, and TCL for transaction control. DDL commands include CREATE, DROP, ALTER, TRUNCATE, COMMENT, and RENAME, while DML commands include INSERT, UPDATE, DELETE, and LOCK. Constraints in SQL ensure data integrity and can be applied at the column or table level, including NOT NULL, UNIQUE, PRIMARY KEY, and FOREIGN KEY.

Uploaded by

sanjeevibcab
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

SQL Comments (1)

SQL commands are categorized into five types: DDL for defining database structures, DQL for querying data, DML for manipulating data, DCL for controlling access, and TCL for transaction control. DDL commands include CREATE, DROP, ALTER, TRUNCATE, COMMENT, and RENAME, while DML commands include INSERT, UPDATE, DELETE, and LOCK. Constraints in SQL ensure data integrity and can be applied at the column or table level, including NOT NULL, UNIQUE, PRIMARY KEY, and FOREIGN KEY.

Uploaded by

sanjeevibcab
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

SQL Commands

SQL Commands are mainly categorized into five categories:


1. DDL – Data Definition Language
2. DQL – Data Query Language
3. DML – Data Manipulation Language
4. DCL – Data Control Language
5. TCL – Transaction Control Language

DDL (Data Definition Language)


It simply deals with descriptions of the database schema and is used to create and
modify the structure of database objects in the database.
DDL is a set of SQL commands used to create, modify, and delete database
structures but not data.

List of DDL Commands:


Here are all the main DDL (Data Definition Language) commands along with their
syntax:
Command Description Syntax

Create database or its objects (table, index, CREATE TABLE table_name (column1 dat
CREATE column2 data_type, ...);
function, views, store procedure, and triggers)

DROP Delete objects from the database DROP TABLE table_name;

ALTER TABLE table_name ADD COLU


ALTER Alter the structure of the database column_name data_type;

Remove all records from a table, including all


TRUNCATE TRUNCATE TABLE table_name;
spaces allocated for the records are removed

COMMENT Add comments to the data dictionary COMMENT 'comment_text' ON TABLE tabl

RENAME TABLE old_table_name TO


RENAME Rename an object existing in the database new_table_name;

SQL CREATE TABLE Example


The following example creates a table called "Persons" that contains five columns: PersonID,
LastName, FirstName, Address, and City:

Example

CREATE TABLE Persons (


PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
The empty "Persons" table will now look like this:

PersonID LastName FirstName Address City

DROP DATABASE Example


The following SQL statement drops the existing database "testDB":

Example

DROP DATABASE testDB;

SQL DROP TABLE Example


The following SQL statement drops the existing table "Shippers":

Example

DROP TABLE Shippers;

SQL ALTER TABLE Statement


The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.

The ALTER TABLE statement is also used to add and drop various constraints on an existing
table.

ALTER TABLE - ADD Column


To add a column in a table, use the following syntax:

ALTER TABLE table_name


ADD column_name datatype;

The following SQL adds an "Email" column to the "Customers" table:

Example
ALTER TABLE Customers
ADD Email varchar(255);

ALTER TABLE - DROP COLUMN


To delete a column in a table, use the following syntax (notice that some database systems don't
allow deleting a column):

ALTER TABLE table_name


DROP COLUMN column_name;

The following SQL deletes the "Email" column from the "Customers" table:

Example

ALTER TABLE Customers


DROP COLUMN Email;

SQL ALTER TABLE Example


Look at the "Persons" table:

ID LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Now we want to add a column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

ALTER TABLE Persons


ADD DateOfBirth date;

Notice that the new column, "DateOfBirth", is of type date and is going to hold a date. The data
type specifies what type of data the column can hold. The "Persons" table will now look like this:
ID LastName FirstName Address City DateOfBirth

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Change Data Type Example


Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

ALTER TABLE Persons


ALTER COLUMN DateOfBirth year;

Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two- or
four-digit format.

DROP COLUMN Example


Next, we want to delete the column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

ALTER TABLE Persons


DROP COLUMN DateOfBirth;

The "Persons" table will now look like this:

ID LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger


DQL (Data Query Language)
It are used for performing queries on the data within schema objects.
The purpose of the DQL Command is to get some schema relation based on the query passed
to it.
We can define DQL as follows it is a component of SQL statement that allows getting data
from the database and imposing order upon it.

This command allows getting the data out of the database to perform operations with it.
When a SELECT is fired against a table or tables the result is compiled into a further
temporary table, which is displayed or perhaps received by the program i.e. a front-end.

DQL Command
There is only one DQL command in SQL i.e.
Command Description Syntax

It is used to retrieve data SELECT column1, column2, ...FROM


SELECT
from the database table_name WHERE condition;

The SQL SELECT Statement


The SELECT statement is used to select data from a database.

Example

Return data from the Customers table:

SELECT CustomerName, City FROM Customers;

Custome CustomerN ContactNa Address City PostalC Count


rID ame me ode ry

1 Alfreds Maria Obere Str. Berli 12209 Germa


Futterkiste Anders 57 n ny

2 Ana Trujillo Ana Avda. de Méxi 05021 Mexic


Emparedado Trujillo la co o
s y helados Constituci D.F.
ón 2222

3 Antonio Antonio Mataderos Méxi 05023 Mexic


Moreno Moreno 2312 co o
Taquería D.F.

4 Around the Thomas 120 Lond WA1 UK


Horn Hardy Hanover on 1DP
Sq.

5 Berglunds Christina Berguvsvä Luleå S-958 22 Swede


snabbköp Berglund gen 8 n

DML (Data Manipulation Language)


The SQL commands that deal with the manipulation of data present in the database belong to
DML or Data Manipulation Language.
It is the component of the SQL statement that controls access to data and to the database.
Basically, DCL statements are grouped with DML statements.

List of DML commands


Here are all the main DML (Data Manipulation Language) commands along with their syntax:
Command Description Syntax

Insert data into a INSERT INTO table_name (column1, column2, ...)


INSERT
table VALUES (value1, value2, ...);

UPDATE Update existing data UPDATE table_name SET column1 = value1,


Command Description Syntax

within a table column2 = value2 WHERE condition;

Delete records from


DELETE DELETE FROM table_name WHERE condition;
a database table

Table control
LOCK LOCK TABLE table_name IN lock_mode;
concurrency

Call a PL/SQL or
CALL CALL procedure_name(arguments);
JAVA subprogram

EXPLAIN Describe the access EXPLAIN PLAN FOR SELECT * FROM


PLAN path to data table_name;

INSERT INTO Example


The following SQL statement inserts a new record in the "Customers" table:

Example

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)


VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');

The selection from the "Customers" table will now look like this:

Custome CustomerN ContactNa Address City PostalCo Count


rID ame me de ry

89 White Karl 305 - Seattle 98128 USA


Clover Jablonski 14th
Markets Ave. S.
Suite 3B

90 Wilman Kala Matti Keskusk Helsink 21240 Finlan


Karttunen atu 45 i d

91 Wolski Zbyszek ul. Walla 01-012 Poland


Filtrowa
68

92 Cardinal Tom B. Skagen Stavan 4006 Norwa


Erichsen 21 ger y

Note:
The CustomerID column is an auto-increment field and will be generated automatically when a new
record is inserted into the table.

Insert Multiple Rows


It is also possible to insert multiple rows in one statement.

To insert multiple rows of data, we use the same INSERT INTO statement, but with multiple
values:

Example

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)


VALUES
('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway'),
('Greasy Burger', 'Per Olsen', 'Gateveien 15', 'Sandnes', '4306', 'Norway'),
('Tasty Tee', 'Finn Egan', 'Streetroad 19B', 'Liverpool', 'L1 0AA', 'UK');

Make sure you separate each set of values with a comma ,.

The selection from the "Customers" table will now look like this:

Custome CustomerN ContactNa Address City PostalCo Count


rID ame me de ry

89 White Karl 305 - Seattle 98128 USA


Clover Jablonski 14th
Markets Ave. S.
Suite 3B

90 Wilman Kala Matti Keskusk Helsink 21240 Finlan


Karttunen atu 45 i d

91 Wolski Zbyszek ul. Walla 01-012 Poland


Filtrowa
68

92 Cardinal Tom B. Skagen Stavan 4006 Norwa


Erichsen 21 ger y

93 Greasy Per Olsen Gateveie Sandne 4306 Norwa


Burger n 15 s y

94 Tasty Tee Finn Egan Streetroa Liverp L1 0AA UK


d 19B ool

The SQL UPDATE EXAMPLE


Demo Database
Below is a selection from the Customers table used in the examples:

Custome CustomerN ContactNa Address City PostalC Count


rID ame me ode ry

1 Alfreds Maria Obere Str. Berli 12209 Germa


Futterkiste Anders 57 n ny

2 Ana Trujillo Ana Avda. de Méxi 05021 Mexic


Emparedado Trujillo la co o
s y helados Constituci D.F.
ón 2222

3 Antonio Antonio Mataderos Méxi 05023 Mexic


Moreno co
Taquería Moreno 2312 D.F. o

4 Around the Thomas 120 Lond WA1 UK


Horn Hardy Hanover on 1DP
Sq.

5 Berglunds Christina Berguvsvä Luleå S-958 22 Swede


snabbköp Berglund gen 8 n

UPDATE Table
The following SQL statement updates the first customer (CustomerID = 1) with a new contact
person and a new city.

Example

UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;

The selection from the "Customers" table will now look like this:

Custome CustomerN ContactNa Address City PostalC Count


rID ame me ode ry

1 Alfreds Alfred Obere Str. Frankf 12209 Germa


Futterkiste Schmidt 57 urt ny

2 Ana Trujillo Ana Avda. de Méxic 05021 Mexic


Emparedado Trujillo la o D.F. o
s y helados Constituci
ón 2222

3 Antonio Antonio Mataderos Méxic 05023 Mexic


Moreno Moreno 2312 o D.F. o
Taquería
4 Around the Thomas 120 Londo WA1 UK
Horn Hardy Hanover n 1DP
Sq.

5 Berglunds Christina Berguvsvä Luleå S-958 22 Swede


snabbköp Berglund gen 8 n

SQL DELETE :
Demo Database
Below is a selection from the Customers table used in the examples:

Custome CustomerN ContactNa Address City PostalC Count


rID ame me ode ry

1 Alfreds Maria Obere Str. Berli 12209 Germa


Futterkiste Anders 57 n ny

2 Ana Trujillo Ana Avda. de Méxi 05021 Mexic


Emparedado Trujillo la co o
s y helados Constituci D.F.
ón 2222

3 Antonio Antonio Mataderos Méxi 05023 Mexic


Moreno Moreno 2312 co o
Taquería D.F.

4 Around the Thomas 120 Lond WA1 UK


Horn Hardy Hanover on 1DP
Sq.

5 Berglunds Christina Berguvsvä Luleå S-958 22 Swede


snabbköp Berglund gen 8 n
SQL DELETE Example
The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers"
table:

Example

DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

The "Customers" table will now look like this:

Custome CustomerN ContactNa Address City PostalC Count


rID ame me ode ry

2 Ana Trujillo Ana Avda. de Méxi 05021 Mexic


Emparedado Trujillo la co o
s y helados Constituci D.F.
ón 2222

3 Antonio Antonio Mataderos Méxi 05023 Mexic


Moreno Moreno 2312 co o
Taquería D.F.

4 Around the Thomas 120 Lond WA1 UK


Horn Hardy Hanover on 1DP
Sq.

5 Berglunds Christina Berguvsvä Luleå S-958 22 Swede


snabbköp Berglund gen 8 n

SQL Constraints
SQL constraints are used to specify rules for the data in a table.

Constraints are used to limit the type of data that can go into a table.

This ensures the accuracy and reliability of the data in the table. If there is any violation between
the constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a column, and
table level constraints apply to the whole table.

The following constraints are commonly used in SQL:

 NOT NULL - Ensures that a column cannot have a NULL value


 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies
each row in a table
 FOREIGN KEY - Prevents actions that would destroy links between tables
 CHECK - Ensures that the values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column if no value is specified
 CREATE INDEX - Used to create and retrieve data from the database very quickly
SQL PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquely identifies each record in a table.

Primary keys must contain UNIQUE values, and cannot contain NULL values.

A table can have only ONE primary key; and in the table, this primary key can consist of single
or multiple columns (fields).

SQL PRIMARY KEY on CREATE TABLE


The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is
created:

MySQL:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint
on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:


CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);

Note: In the example above there is only ONE PRIMARY KEY (PK_Person). However, the
VALUE of the primary key is made up of TWO COLUMNS (ID + LastName).

SQL PRIMARY KEY on ALTER TABLE


To create a PRIMARY KEY constraint on the "ID" column when the table is already created, use
the following SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ADD PRIMARY KEY (ID);

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint
on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);

Note: If you use ALTER TABLE to add a primary key, the primary key column(s) must have
been declared to not contain NULL values (when the table was first created).

DROP a PRIMARY KEY Constraint


To drop a PRIMARY KEY constraint, use the following SQL:

MySQL:

ALTER TABLE Persons


DROP PRIMARY KEY;

SQL Server / Oracle / MS Access:


ALTER TABLE Persons
DROP CONSTRAINT PK_Person;

SQL FOREIGN KEY Constraint


The FOREIGN KEY constraint is used to prevent actions that would destroy links between
tables.

A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY
KEY in another table.

The table with the foreign key is called the child table, and the table with the primary key is
called the referenced or parent table.

Look at the following two tables:

Persons Table

PersonID LastName FirstName Age

1 Hansen Ola 30

2 Svendson Tove 23

3 Pettersen Kari 20

Orders Table

OrderI OrderNumbe PersonI


D r D

1 77895 3

2 44678 3

3 22456 2

4 24562 1

Notice that the "PersonID" column in the "Orders" table points to the "PersonID" column in the
"Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.

The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.

The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key
column, because it has to be one of the values contained in the parent table.

SQL FOREIGN KEY on CREATE TABLE


The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders"
table is created:

MySQL:

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

SQL Server / Oracle / MS Access:

CREATE TABLE Orders (


OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
);

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint
on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID)
);

SQL FOREIGN KEY on ALTER TABLE


To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders" table is
already created, use the following SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders


ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint
on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders


ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

DROP a FOREIGN KEY Constraint


To drop a FOREIGN KEY constraint, use the following SQL:

MySQL:

ALTER TABLE Orders


DROP FOREIGN KEY FK_PersonOrder;

SQL Server / Oracle / MS Access:

ALTER TABLE Orders


DROP CONSTRAINT FK_PersonOrder;

SQL CHECK Constraint


The CHECK constraint is used to limit the value range that can be placed in a column.

If you define a CHECK constraint on a column it will allow only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on
values in other columns in the row.

SQL CHECK on CREATE TABLE


The following SQL creates a CHECK constraint on the "Age" column when the "Persons" table
is created. The CHECK constraint ensures that the age of a person must be 18, or older:

MySQL:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);

SQL Server / Oracle / MS Access:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int CHECK (Age>=18)
);

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);

SQL CHECK on ALTER TABLE


To create a CHECK constraint on the "Age" column when the table is already created, use the
following SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ADD CHECK (Age>=18);

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');

DROP a CHECK Constraint


To drop a CHECK constraint, use the following SQL:

SQL Server / Oracle / MS Access:

ALTER TABLE Persons


DROP CONSTRAINT CHK_PersonAge;

MySQL:

ALTER TABLE Persons


DROP CHECK CHK_PersonAge;

SQL DEFAULT Constraint


The DEFAULT constraint is used to set a default value for a column.

The default value will be added to all new records, if no other value is specified.

SQL DEFAULT on CREATE TABLE


The following SQL sets a DEFAULT value for the "City" column when the "Persons" table is
created:

My SQL / SQL Server / Oracle / MS Access:


CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);

The DEFAULT constraint can also be used to insert system values, by using functions
like GETDATE():

CREATE TABLE Orders (


ID int NOT NULL,
OrderNumber int NOT NULL,
OrderDate date DEFAULT GETDATE()
);

SQL DEFAULT on ALTER TABLE


To create a DEFAULT constraint on the "City" column when the table is already created, use the
following SQL:

MySQL:

ALTER TABLE Persons


ALTER City SET DEFAULT 'Sandnes';

SQL Server:

ALTER TABLE Persons


ADD CONSTRAINT df_City
DEFAULT 'Sandnes' FOR City;

MS Access:

ALTER TABLE Persons


ALTER COLUMN City SET DEFAULT 'Sandnes';

Oracle:

ALTER TABLE Persons


MODIFY City DEFAULT 'Sandnes';
DROP a DEFAULT Constraint
To drop a DEFAULT constraint, use the following SQL:

MySQL:

ALTER TABLE Persons


ALTER City DROP DEFAULT;

SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ALTER COLUMN City DROP DEFAULT;

SQL CREATE INDEX Statement


The CREATE INDEX statement is used to create indexes in tables.

Indexes are used to retrieve data from the database more quickly than otherwise. The users
cannot see the indexes, they are just used to speed up searches/queries.

Note: Updating a table with indexes takes more time than updating a table without (because the indexes
also need an update). So, only create indexes on columns that will be frequently searched against.

CREATE INDEX Syntax

Creates an index on a table. Duplicate values are allowed:

CREATE INDEX index_name


ON table_name (column1, column2, ...);
CREATE UNIQUE INDEX Syntax

Creates a unique index on a table. Duplicate values are not allowed:

CREATE UNIQUE INDEX index_name


ON table_name (column1, column2, ...);

Note: The syntax for creating indexes varies among different databases. Therefore: Check the
syntax for creating indexes in your database.
CREATE INDEX Example
The SQL statement below creates an index named "idx_lastname" on the "LastName" column in
the "Persons" table:

CREATE INDEX idx_lastname


ON Persons (LastName);

If you want to create an index on a combination of columns, you can list the column names
within the parentheses, separated by commas:

CREATE INDEX idx_pname


ON Persons (LastName, FirstName);
DROP INDEX Statement

The DROP INDEX statement is used to delete an index in a table.

MS Access:

DROP INDEX index_name ON table_name;

SQL Server:

DROP INDEX table_name.index_name;

DB2/Oracle:

DROP INDEX index_name;

MySQL:

ALTER TABLE table_name


DROP INDEX index_name;

Types of Keys in Relational Model


Keys are one of the basic requirements of a relational database model. It is widely used to
identify the tuples(rows) uniquely in the table. We also use keys to set up relations amongst
various columns and tables of a relational database.
Different Types of Database Keys
 Candidate Key
 Primary Key
 Super Key
 Alternate Key
 Foreign Key
 Composite Key

Candidate Key

The minimal set of attributes that can uniquely identify a tuple is known as a candidate key.
For Example, STUD_NO in STUDENT relation.
 It is a minimal super key.
 It is a super key with no repeated data is called a candidate key.
 The minimal set of attributes that can uniquely identify a record.
 It must contain unique values.
 It can contain NULL values.
 Every table must have at least a single candidate key.
 A table can have multiple candidate keys but only one primary key.
 The value of the Candidate Key is unique and may be null for a tuple.
 There can be more than one candidate key in a relationship.
Example:
STUD_NO is the candidate key for relation STUDENT.
Table STUDENT

STUD_NO SNAME ADDRESS PHONE

1 Shyam Delhi 123456789

2 Rakesh Kolkata 223365796

3 Suraj Delhi 175468965


 The candidate key can be simple (having only one attribute) or composite as well.
Example:
{STUD_NO, COURSE_NO} is a composite
candidate key for relation STUDENT_COURSE.
Table STUDENT_COURSE

STUD_NO TEACHER_NO COURSE_NO

1 001 C001

2 056 C005
Note: In SQL Server a unique constraint that has a nullable column, allows the value ‘ null ‘
in that column only once . That’s why the STUD_PHONE attribute is a candidate here, but can
not be a ‘null’ value in the primary key attribute.

Primary Key
There can be more than one candidate key in relation out of which one can be chosen as the
primary key. For Example, STUD_NO, as well as STUD_PHONE, are candidate keys for
relation STUDENT but STUD_NO can be chosen as the primary key (only one out of many
candidate keys).
 It is a unique key.
 It can identify only one tuple (a record) at a time.
 It has no duplicate values, it has unique values.
 It cannot be NULL.
 Primary keys are not necessarily to be a single column; more than one column can also be a
primary key for a table.
Example:
STUDENT table -> Student(STUD_NO, SNAME,
ADDRESS, PHONE) , STUD_NO is a primary key
Table STUDENT

STUD_NO SNAME ADDRESS PHONE

1 Shyam Delhi 123456789

2 Rakesh Kolkata 223365796

3 Suraj Delhi 175468965

Super Key

The set of attributes that can uniquely identify a tuple is known as Super Key. For Example,
STUD_NO, (STUD_NO, STUD_NAME), etc. A super key is a group of single or multiple
keys that identifies rows in a table. It supports NULL values.
 Adding zero or more attributes to the candidate key generates the super key.
 A candidate key is a super key but vice versa is not true.
 Super Key values may also be NULL.
Example:
Consider the table shown above.
STUD_NO+PHONE is a super key.
Relation between Primary Key, Candidate Key, and Super Key

Alternate Key

The candidate key other than the primary key is called an alternate key .
 All the keys which are not primary keys are called alternate keys.
 It is a secondary key.
 It contains two or more fields to identify two or more records.
 These values are repeated.
 Eg:- SNAME, and ADDRESS is Alternate keys
Example:
Consider the table shown above.
STUD_NO, as well as PHONE both,
are candidate keys for relation STUDENT but
PHONE will be an alternate key
(only one out of many candidate keys).
Primary Key, Candidate Key, and Alternate Key

Foreign Key

If an attribute can only take the values which are present as values of some other attribute, it
will be a foreign key to the attribute to which it refers. The relation which is being referenced
is called referenced relation and the corresponding attribute is called referenced attribute. The
referenced attribute of the referenced relation should be the primary key to it.
 It is a key it acts as a primary key in one table and it acts as
secondary key in another table.
 It combines two or more relations (tables) at a time.
 They act as a cross-reference between the tables.
 For example, DNO is a primary key in the DEPT table and a non-key in EMP
Example:
Refer Table STUDENT shown above.
STUD_NO in STUDENT_COURSE is a
foreign key to STUD_NO in STUDENT relation.
Table STUDENT_COURSE
STUD_NO TEACHER_NO COURSE_NO

1 005 C001

2 056 C005
It may be worth noting that, unlike the Primary Key of any given relation, Foreign Key can be
NULL as well as may contain duplicate tuples i.e. it need not follow uniqueness constraint. For
Example, STUD_NO in the STUDENT_COURSE relation is not unique. It has been repeated
for the first and third tuples. However, the STUD_NO in STUDENT relation is a primary key
and it needs to be always unique, and it cannot be null.

Relation between Primary Key and Foreign Key

Composite Key

Sometimes, a table might not have a single column/attribute that uniquely identifies all the
records of a table. To uniquely identify rows of a table, a combination of two or more
columns/attributes can be used. It still can give duplicate values in rare cases. So, we need to
find the optimal set of attributes that can uniquely identify rows in a table.
 It acts as a primary key if there is no primary key in a table
 Two or more attributes are used together to make a composite key .
 Different combinations of attributes may give different accuracy in terms of identifying the
rows uniquely.
Example:
FULLNAME + DOB can be combined
together to access the details of a student.

Different Types of Keys

You might also like