The Wayback Machine - https://web.archive.org/web/20241123004646/https://www.geeksforgeeks.org/sql-alternate-key/
Open In App

SQL – ALTERNATE KEY

Last Updated : 26 Jul, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Keys are an important part of any Relational Database. There are various types of keys and among one of these is the Alternate Key. The keys that contain all the properties needed to become a Candidate Key are known as Alternate Keys. These are basically secondary Candidate Keys that can uniquely identify a row in a table. So, Alternate Keys are also sometimes known as “Secondary Keys”.

In other words, we can define the Alternate key as the set of Candidate Keys other than the Primary Key. There can be many Candidate Keys for a given table and out of all these the Database Administrators selects only one of these as the Primary Key. Hence, the other Candidate Keys which are not used as a Primary Key are the “Alternate Keys”. 

Some important points about Alternate Keys are as follows :

  1. A Primary Key can’t be an Alternate Key. For a table with a single Candidate Key which has to be the Primary Key will not contain any Alternate Key.
  2. A Foreign Key can’t be an Alternate Key as it is only used to reference another table.
  3. The alternate Key should be unique.
  4. An Alternate Key can be a set of a single attribute or multiple attributes.
  5. It can be NULL as well.

In this article, we are going to see how to create an ALTERNATE Key in SQL using sample tables as shown.

Sample Input : Consider the Table Customer Information which consists data about customers who bought products from an E-Commerce site. This table is referencing the Product Information table to know about the details of the product bought by a customer. The common attribute used for referencing is “Product ID” which is also termed as Foreign Key.

         Product Information 
Product ID Product Name Price
1001 Washing Soap 25
1020 Shampoo 150
1030 Notebook 200
1045 Headphone 1000
                                                                  Customer Information
Customer ID Customer Name Email Address Shipping Address Pan Number Product ID
1 Madhulika abc@gmail.com XYZ-Colony, Patna XXABX10011 1030
2 Tanmoy tdq@gmail.com ABC-Colony, Guwahati DDABX10034 1001
3 Ritik def@gmail.com XYZ_Street, Chennai ACQBX10555 1045
4 Satadru sm11@gmail.com Park_Street, Kolkata ZZABX20035 1045

In the Customer Information Table, Customer ID, Pan Number, Email Address are unique as it can uniquely identify a row in the given table. PAN Number is unique for every person and Customer ID is also a unique number provided by E-Commerce sites to distinguish among tons of customers registered in their shopping site. 

A user can register on the shopping site using only a single E-Mail Address. If he/she wants to create another account using the same E-Mail will show a message, “An account with this E-Mail Address already exists, Please Login”. So, every consumer will have a unique E-Mail Address. Hence, all these attributes can uniquely identify a row in a table.

The candidate key set for the above table is : { Customer ID, Pan Number, Email Address }

Say, the Data Base Administrator of this E-Commerce site picked Customer ID as the Primary Key. Therefore, PAN Number and E-Mail Address will be Alternate Keys or Secondary Keys. Alternate Key has all the properties to become a Primary Key and so is an alternate option.

ALTERNATE Keys in SQL are defined using the SQL constraint UNIQUE.

UNIQUE(col_name(s))

col_name(s): The name of the column(s) in the table which need to be unique.

BASIC SQL QUERY :

1. Creating a Database

CREATE DATABASE database_name

2. Creating a Table

CREATE TABLE Table_name(
col_1 TYPE col_1_constraint,
col_2 TYPE col_2 constraint,
col_3 TYPE UNIQUE,
col_4 TYPE REFERENCES Table_Name(col_name),
.....
)

col: The name of the columns.
TYPE: Data type whether an integer, variable character, etc
col_constraint: Constraints in SQL like PRIMARY KEY, NOT NULL, UNIQUE, REFERENCES, etc.
col_3: Defining an ALTERNATE KEY using constraint UNIQUE
col_4: Defining an FOREIGN KEY using constraint REFERENCES

3. Inserting into a Table

INSERT INTO Table_name
VALUES(val_1, val_2, val_3, ..........)

val: Values in particular column

4. View The Table

SELECT * FROM Table_name

Output :

Product Table

Customer Table

A pictorial view of all the keys present in the table is shown below :

KEYS


Previous Article
Next Article

Similar Reads

Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
Structured Query Language (SQL): Structured Query Language (SQL) has a specific design motive for defining, accessing and changement of data. It is considered as non-procedural, In that case the important elements and its results are first specified without taking care of the how they are computed. It is implemented over the database which is drive
2 min read
Configure SQL Jobs in SQL Server using T-SQL
In this article, we will learn how to configure SQL jobs in SQL Server using T-SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-SQL in detail. Let's discuss it one by one. Introduction :SQL Server Agent is a component used for database task automation. For Example, If we need to perform index maintenance on Production ser
7 min read
Can a Composite Key be a Foreign Key in Another Table?
Answer: Yes, a composite key can be used as a foreign key in another table within a relational database.In SQL databases, a composite key comprises multiple columns to uniquely identify rows in a table. To establish a foreign key referencing a composite key: Create the Parent TableDefine the parent table with a composite key. CREATE TABLE ParentTab
1 min read
Primary key in MS SQL Server
A table has a particular number of columns and each column has n number of rows. At times, there might be a probability of repeated rows in a column. For example, a column named identification number has repeated rows. To avoid the duplication of rows, the concept of a key has been introduced. A key is an attribute or a set of attributes that can b
2 min read
SQL Query to Check or Find the Column Name Which Is Primary Key Column
Structured Query Language or SQL, is composed of commands that enable users to create database and table structures, perform various types of data manipulation and data administration and query the database to extract useful information. We will start with creating the database "geeksforgeeks" and then we will proceed with creating a table "interns
2 min read
SQL Query to Drop Unique Key Constraints Using ALTER Command
Here, we see how to drop unique constraints using alter command. ALTER is used to add, delete/drop or modify columns in the existing table. It is also used to add and drop various constraints on the existing table. Syntax : ALTER TABLE table_name DROP CONSTRAINT unique_constraint; For instance, consider the below table 'Employee'. Create a Table: C
2 min read
Composite Key in SQL
To know what a composite key is we need to have the knowledge of what a primary key is, a primary key is a column that has a unique and not null value in an SQL table. Now a composite key is also a primary key, but the difference is that it is made by the combination of more than one column to identify the particular row in the table. Composite Key
2 min read
SQL Query to Add Unique key Constraints Using ALTER Command
Here we will see how to add unique key constraint to a column(s) of a MS SQL Server's database with the help of a SQL query using ALTER clause. For the demonstration purpose, we will be creating a demo table in a database called "geeks". Creating the Database : Use the below SQL statement to create a database called geeks: CREATE DATABASE geeks; Us
2 min read
SQL Query to Create Table With a Primary Key
A primary key uniquely identifies each row table. It must contain unique and non-NULL values. A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called composite keys. To create a Primary key in the table, we have to use a keyword; "PRIMARY KEY ( )" Query:
2 min read
Change Primary Key Column in SQL Server
Primary Key refers to the column of a table that uniquely identifies a row in a table. It contains unique values and can not contain NULL values. For the purpose of the demonstration, we will be creating geeks for geeks table in a database called “geeks“. Step 1: Creating the database The database is created in SQL Server using the following comman
2 min read
How to Create a Composite Primary Key in SQL Server?
In this article, We will learn what is a Composite Primary Key and How will create a Composite Primary Key. As We know a Primary key is the Candidate key that is selected to uniquely identify a row in a table. A And Primary Key does not allow NULL value. Composite Primary KeyWhen two or more Columns are together Identify the unique row in a table K
3 min read
How to Reset SQL Primary Key Sequence When It Falls Out of Sync?
In SQL databases, primary keys play a critical role in maintaining data integrity and ensuring uniqueness. However, primary key sequences can sometimes fall out of sync, leading to potential issues. In this article, we'll delve into the reasons behind primary key sequence misalignment and provide a comprehensive guide on how to effectively reset th
3 min read
SQL PRIMARY KEY Constraint
SQL PRIMARY KEY constraint uniquely identifies each record in a database table. PRIMARY KEY in SQLPRIMARY KEY in SQL is a column (or group of columns) that uniquely identifies the records in that table. A primary key must contain unique values and can not have any NULL value. There can only be one primary key in a table, but that primary key can co
3 min read
How to Create a Table With a Foreign Key in SQL?
To create a table with a foreign key in SQL, use the FOREIGN KEY constraint on the column which is the desired foreign key. SyntaxTo create a table with a foreign key in SQL, use the following syntax: CREATE TABLE TABLE_NAME( Column 1 datatype, Column 2 datatype, Column 3 datatype FOREIGN KEY REFERENCES Table_name(Column name), .. Column n ) Create
3 min read
SQL FOREIGN KEY Constraint
The SQL FOREIGN KEY constraint The foreign key constraint ensures that the values in the foreign key column match the values in the primary key column of the referenced table, maintaining referential integrity. Foreign Key in SQLA foreign key is a column or a combination of columns in a table that establishes a link between two tables in a relation
3 min read
SQL Query to Drop Foreign Key Constraint Using ALTER Command
A foreign key is included in the structure of a table, to connect multiple tables by referring to the primary key of another table. Sometimes, you might want to remove the primary key constraint from a table for performance issues or other requirements. A foreign key constraint can be removed from a table using the ALTER TABLE command and DROP CONS
3 min read
SQL Query to Add Foreign Key Constraints Using ALTER Command
In relational databases, a Foreign Key Constraint is a fundamental concept that defines a relationship between two tables. It ensures that the value of one or more columns in a child table corresponds to the value in a primary key or unique key in a parent table. In this article, we will look into how we can add a foreign key constraint using the A
3 min read
SQL Query to Remove Primary Key
Removing a primary key constraint from a table in SQL Server involves several steps to ensure the database schema is correctly updated. A primary key constraint uniquely identifies each record in a table and removing it can impact data integrity and relationships. In this article, we will see how to remove a primary key constraint from a table in S
3 min read
Foreign key in MS SQL Server
A foreign key in SQL Server plays a crucial role in establishing and enforcing relationships between tables. It is a column or a set of columns in a table that references the primary key or a unique key in another table. By using foreign key constraints the SQL Server keeps data consistent between related tables. In this article, We will learn abou
6 min read
SQL SERVER – Input and Output Parameter For Dynamic SQL
An Input Parameter can influence the subset of rows it returns from a select statement within it. A calling script can get the value of an output parameter. An aggregate function or any computational expression within the stored process can be used to determine the value of the output parameter. A parameter whose value is given into a stored proced
3 min read
Difference between T-SQL and PL-SQL
1. Transact SQL (T-SQL) : T-SQL is an abbreviation for Transact Structure Query Language. It is a product by Microsoft and is an extension of SQL Language which is used to interact with relational databases. It is considered to perform best with Microsoft SQL servers. T-SQL statements are used to perform the transactions to the databases. T-SQL has
3 min read
SQL - SELECT from Multiple Tables with MS SQL Server
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables. If we consider table1 contains m rows and table2 contains n
3 min read
How to Execute SQL Server Stored Procedure in SQL Developer?
A stored procedure is a set of (T-SQL ) statements needed in times when we are having the repetitive usage of the same query. When there is a need to use a large query multiple times we can create a stored procedure once and execute the same wherever needed instead of writing the whole query again. In this article let us see how to execute SQL Serv
2 min read
SQL Query to Check if Date is Greater Than Today in SQL
In this article, we will see the SQL query to check if DATE is greater than today's date by comparing date with today's date using the GETDATE() function. This function in SQL Server is used to return the present date and time of the database system in a ‘YYYY-MM-DD hh:mm: ss. mmm’ pattern. Features: This function is used to find the present date a
2 min read
SQL Query to Add a New Column After an Existing Column in SQL
Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve data from relational databases like MySQL, Oracle, SQL Server, Postgres, etc. In Microsoft SQL Server, we can change the order of the columns and can add a new column by using ALTER command. ALTER TABLE is used to add, delete/drop or modif
3 min read
SQL Query to Convert Rows to Columns in SQL Server
In this article we will see, how to convert Rows to Column in SQL Server. In a table where many columns have the have same data for many entries in the table, it is advisable to convert the rows to column. This will help to reduce the table and make the table more readable. For example, Suppose we have a table given below: NAMECOLLEGEROLL NUMBERSUB
2 min read
How to SQL Select from Stored Procedure using SQL Server?
There may be situations in SQL Server where you need to use a stored procedure to get data from a SQL query. For direct data selection from a stored procedure within a query, SQL Server offers options like OPENQUERY and OPENROWSET. The usual way is running the stored procedure independently and then querying the outcomes. The idea of utilizing SQL
3 min read
SQL Quiz : Practice SQL Questions Online
This SQL quiz covers various topics like SQL basics, CRUD operations, operators, aggregation functions, constraints, joins, indexes, transactions, and query-based scenarios. We've included multiple-choice questions, fill-in-the-blank questions, and interactive coding challenges to keep things interesting and challenging. Whether you're a beginner l
3 min read
BULK INSERT in SQL Server(T-SQL command)
BULK INSERT in SQL Server(T-SQL command): In this article, we will cover bulk insert data from csv file using the T-SQL command in the SQL server and the way it is more useful and more convenient to perform such kind of operations. Let's discuss it one by one.  ConditionSometimes there is a scenario when we have to perform bulk insert data from .cs
3 min read
Difference between SQL and T-SQL
SQL (Structured Query Language) is the standard language for managing and manipulating relational databases, enabling operations like querying, updating, and deleting data. T-SQL (Transact-SQL), an extension of SQL developed by Microsoft, adds advanced features and procedural capabilities specifically for SQL Server. In this article, We will learn
4 min read
Article Tags :
three90RightbarBannerImg