European Windows 2019 Hosting BLOG

BLOG about Windows 2019 Hosting and SQL 2019 Hosting - Dedicated to European Windows Hosting Customer

European SQL Server 2022 Hosting :: Types of Keys in Database

clock May 15, 2025 10:23 by author Peter

DBMS keys
An characteristic on a table column that is used to identify a row or record inside a collection of rows is called a key in a database. To put it another way, a key in a database management system is a field or columns that are used to uniquely identify a record in a table. Data and records are kept in tabular form in relational databases, which are composed of rows and columns.
Depending on the condition or demand, it is utilized to get records or data rows from the data table. A key offers a variety of constraints, such as a column that is unable to hold null or duplicate entries. Relationships between various database tables or views are also created using keys. A row in a database table can also be uniquely identified by a combination of one or more of the table's columns using database keys.

DBMS supports multiple types of keys and each of these types has a different purpose and use case. This post explains the different types of keys in databases, their meanings, and how to set and use these different types of keys in SQL.
Types of Keys

Databases support ten different types of keys in DBMS and each key has different functionality. The following is a list of ten different types of keys in DBMS.

  • Super Key
  • Minimal Super Key
  • Candidate Key
  • Primary Key
  • Unique Key
  • Alternate Key
  • Composite Key
  • Foreign Key
  • Natural Key
  • Surrogate Key

To understand these different types of keys better, let's start with database tables. We take two tables for a better understanding of the key. The first table is “Branch Info” and the second table is “Student_Information”.

Now we learn about each of these keys and how to use them.

Candidate Key
A candidate key is an attribute or set of attributes that uniquely identifies a record. Among the set of candidates, one candidate key is chosen as the Primary Key. So a table can have multiple candidate keys but each table can have only one primary key.

Example
Possible Candidate Keys in Branch_Info table.
Branch_Id
Branch_Name
Branch_Code

Possible Candidate keys in Student_Information table.
Student_Id
College_Id
Rtu_Roll_No

Primary Key
A primary key uniquely identifies each record in a table and must never be the same for two records. The primary key is a set of one or more fields ( columns) of a table that uniquely identify a record in a database table. A table can have only one primary key and one candidate key can select as a primary key. The primary key should be chosen such that its attributes are never or rarely changed, for example, we can’t select the Student_Id field as a primary key because in some cases Student_Id of a student may be changed.

Example
Primary Key in Branch_Info table:
Branch_Id

Primary Key in Student_Information Table:
College_Id

Alternate Key
Alternate keys are candidate keys that are not selected as the primary keys. The alternate key can also work as a primary key. The alternate key is also called the “Secondary Key”.

Example
Alternate Key in Branch_Info table:
Branch_Name
Branch_Code


Alternate Key in Student_Information table:
Student_Id
Rtu_Roll_No


Unique Key
A unique key is a set of one or more attributes that can be used to uniquely identify the records in the table. The unique key is similar to the primary key but the unique key field can contain a “Null” value but the primary key doesn’t allow a “Null” value. Another difference is that the primary key field contains a clustered index and the unique field contain a non-clustered index.

Example
Possible Unique Key in Branch_Info table.
Branch_Name

Possible Unique Key in Student_Information table:
Rtu_Roll_No

Composite Key
A composite key is a combination of more than one attribute that can be used to uniquely identify each record. It is also known as the “Compound” key. A composite key may be a candidate or primary key.

Example
Composite Key in Branch_Info table.
{ Branch_Name, Branch_Code}

Composite Key in Student_Information table:
{ Student_Id, Student_Name }

Super Key
A super key is a set of one or more than one keys that can be used to uniquely identify the record in the table. A Super key for an entity is a set of one or more attributes whose combined value uniquely identifies the entity in the entity set. A super key is a combining form of the Primary Key, Alternate key, and Unique key, and Primary Key, Unique Key, and Alternate Key are subsets of the super key. A Super Key is simply a non-minimal Candidate Key, that is to say, one with additional columns not strictly required to ensure the uniqueness of the row. A super key can have a single column.

Example
Super Keys in Branch_Info Table.
​Branch_Id
Branch_Name
Branch_Code
{ Branch_Id, Branch_Code }
{ Branch_Name , Branch_Code }


Super Keys in Student_Information Table:
Student_Id
College_Id
Rtu_Roll_No
{ Student_Id, Student_Name}
{ College_Id, Branch_Id }
{ Rtu_Roll_No, Session }


Minimal Super Key
A minimal super key is a minimum set of columns that can be used to uniquely identify a row. In other words the minimum number of columns that can be combined to give a unique value for every row in the table.

Example
Minimal Super Keys in Branch_Info Table.
Branch_Id
Branch_Name
Branch_Code

Minimal Super Keys in Student_Information Table.
Student_Id
College_Id
Rtu_Roll_No

Natural Keys
A natural key is a key composed of columns that actually have a logical relationship to other columns within a table. For example, if we use Student_Id, Student_Name, and Father_Name columns to form a key then it would be a “Natural Key” because there is definitely a relationship between these columns and other columns that exist in the table. Natural keys are often called “Business Keys” or “Domain Keys”.

Surrogate Key

The surrogate key is an artificial key that is used to uniquely identify the record in the table. For example, SQL Server or Sybase database systems contain an artificial key that is known as “Identity”. Surrogate keys are just simple sequential numbers. Surrogate keys are only used to act as primary keys.

Example
Branch_Id is a Surrogate Key in the Branch_Info table and Student_Id is a Surrogate key in the Student_Information table.

Foreign Keys
A foreign key is used to generate the relationship between the tables. Foreign Key is a field in a database table that is the Primary key in another table. A foreign key can accept null and duplicate values.

Example

Branch_Id is a Foreign Key in the Student_Information table the primary key exists in Branch_Info(Branch_Id) table.

You can add a primary key or foreign key or unique key to an existing table using SQL. Here is a detailed article: Add Primary Key, Unique Key, Foreign Key to Existing Table using SQL.

Conclusion

The database generally only contains the Primary Key, Foreign Key, Unique Key, and Surrogate key and other remaining keys are just concepts. A table must have a unique key. According to Dr. E. F. Codd‘s third rule “Every single data element (value) is guaranteed to be accessible logically with a combination of table-name, primary-key (row value), and attribute-name (column value)”. So each table must have keys because the use of keys makes data highly reliable and provide several types of content like unique data and null values. Thanks for reading the article.

HostForLIFEASP.NET SQL Server 2022 Hosting



European SQL Server 2022 Hosting :: How to Use SQL Server to Retrieve Unique Records Without Using Distinct?

clock May 6, 2025 09:41 by author Peter

In this article, I am going to explain how to get unique records without using DISTINCT in SQL Server. This detailed article will cover the following topics as follows,

  1. Introduction
  2. What is DISTINCT in SQL Server?
  3. 9 ways to get unique records without using DISTINCT in SQL Server
  4. Conclusion

First, let's create a database with a table containing some dummy data. Here, I am providing you with the database along with a table containing the records, on which I am showing you the various examples. Let's see.

CREATE DATABASE HostForLIFE_GetUniqueRecords;
PRINT 'New Database ''HostForLIFE_GetUniqueRecords'' Created';
GO

USE [HostForLIFE_GetUniqueRecords];
GO

-->>----Employee Table ------------------->>--
CREATE TABLE [dbo].[Employee] (
    EmployeeID INT IDENTITY (31100, 1),
    EmployerID BIGINT NOT NULL DEFAULT 228866,
    FirstName VARCHAR(50) NOT NULL,
    LastName VARCHAR(50) NOT NULL,
    Email VARCHAR(255) NOT NULL,
    DepartmentID VARCHAR(100) NOT NULL,
    Age INT NOT NULL,
    GrossSalary BIGINT NOT NULL,
    PerformanceBonus BIGINT,
    ContactNo VARCHAR(25),
    PRIMARY KEY (EmployeeID)
);

Next, you can insert data to the tables using the SQL INSERT statement or by adding data directly to the tables in SSMS.

Let's check our table using the following query.

To get the data from the "Employee" table, use the following query.
SELECT * FROM HostForLIFE_GetUniqueRecords..Employee

What is DISTINCT in SQL Server?
In SQL Server, DISTINCT is a keyword used in a SELECT statement to remove duplicate rows from the result set. When you use DISTINCT, the query returns only unique rows based on the columns specified.

Key Points

  • In the SELECT clause, DISTINCT is applied to every column. The combination of values ​​in the columns you specify will be taken into account to determine uniqueness.
  • Since SQL Server has to check each record to filter out duplicates, this can have an impact on performance, especially when working with a huge result set.

SELECT DISTINCT <column1>, <column2>, ...
FROM <Table_Name>
WHERE <Condition_list>;


Example
SELECT DISTINCT Age, DepartmentID
FROM [dbo].[Employee]

9 ways to get unique records without using DISTINCT in SQL Server
Here are nine alternatives to achieve unique records in SQL Server without using the DISTINCT keyword:

Method 1. Using GROUP BY
The GROUP BY clause can be used to group rows that have the same values ​​in specified columns so that duplicates can be filtered out.

Syntax
SELECT <column1>, <column2>, ...
FROM <Table_Name>
GROUP BY <column1>, <column2>, ...;


Example
SELECT Age, DepartmentID
FROM [dbo].[Employee]
GROUP BY Age, DepartmentID

Method 2. Using ROW_NUMBER()
ROW_NUMBER() can be used to get UNIQUE/DISTINCT records in SQL Server.

Syntax
WITH RankedRecords AS (
    SELECT
        <column1>,
        <column2>,
        ROW_NUMBER() OVER (PARTITION BY <column1>, <column2> ORDER BY (SELECT NULL)) AS RowNumber
    FROM
        <Table_Name>
)
SELECT
    <column1>,
    <column2>,
    ...
FROM
    RankedRecords
WHERE
    RowNumber = 1;


Example
WITH RankedRecords AS (
    SELECT
        Age,
        DepartmentID,
        ROW_NUMBER() OVER (PARTITION BY Age, DepartmentID ORDER BY (SELECT NULL)) AS RowNumber
    FROM
        [dbo].[Employee]
)
SELECT
    Age,
    DepartmentID
FROM
    RankedRecords
WHERE
    RowNumber = 1;

Method 3. Using Aggregate Functions
Aggregation functions (such as MIN, MAX, COUNT, etc.) can be used to get unique records on the SQL Server.

Syntax
SELECT
    <column1>,
    <column2>,
    COUNT(*) AS Count
FROM
    <Table_Name>
GROUP BY
    <column1>,
    <column2;


Example
SELECT
    Age,
    DepartmentID,
    COUNT(*) AS Count
FROM
    [dbo].[Employee]
GROUP BY
    Age,
    DepartmentID;

Method 4. Using a Subquery
Subqueries can be used as an alternative to DISTINCT to get unique records in SQL Server.

Syntax
SELECT
    <column1>,
    <column2>
FROM (
    SELECT
        <column1>,
        <column2>
    FROM
        <Table_Name>
) AS subquery
GROUP BY
    <column1>,
    <column2>;

Example
SELECT
    Age,
    DepartmentID
FROM (
    SELECT
        Age,
        DepartmentID
    FROM
        [dbo].[Employee]
) AS subquery
GROUP BY
    Age,
    DepartmentID;

Method 5. Using EXISTS or NON-EXISTS Clause
EXISTS or NON-EXISTS clause can also be used as an alternative to DISTINCT to get unique records in SQL Server.


Syntax

SELECT
    <Column1>,
    <Column2>,
    ...
FROM
    <Table_Name> t1
WHERE
    NOT EXISTS (
        SELECT 1
        FROM
            <Table_Name> t2
        WHERE
            t1.<Column1> = t2.<Column1>
            AND t1.<Column2> = t2.<Column2>
            AND t1.ID > t2.ID  -- Assuming you have an ID column
    );

Example
SELECT
    Age,
    DepartmentID
FROM
    [dbo].[Employee] t1
WHERE
    NOT EXISTS (
        SELECT 1
        FROM
            [dbo].[Employee] t2
        WHERE
            t1.Age = t2.Age
            AND t1.DepartmentID = t2.DepartmentID
            AND t1.EmployeeID > t2.EmployeeID  -- Assuming you have an ID column
    );

Method 6. Using CTE (Common Table Expression)
In SQL Server, CTE (Common Table Expression) can be used in place of DISTINCT to get unique records.

Syntax
WITH UniqueRecords AS (
    SELECT
        <column1>,
        <column2>
    FROM
        <Table_Name>
    GROUP BY
        <column1>, <column2>
)
SELECT *
FROM
    UniqueRecords;


Example
WITH UniqueRecords AS (
    SELECT
        Age,
        DepartmentID
    FROM
        [dbo].[Employee]
    GROUP BY
        Age, DepartmentID
)
SELECT *
FROM
    UniqueRecords;


Method 7. Using SELF-JOIN
In SQL Server, SELF-JOIN can be used instead of DISTINCT to get unique records.


Syntax
SELECT
    T1.<Column1>,
    T1.<Column2>,
    ...
FROM
    <Table_Name> T1
INNER JOIN (
    SELECT
        <Column1>,
        <Column2>,
        MIN(ID) AS min_id
    FROM
        <Table_Name>
    GROUP BY
        <Column1>, <Column2>
) T2
    ON T1.ID = T2.min_id;

Example

SELECT
    T1.Age,
    T1.DepartmentID
FROM
    [dbo].[Employee] T1
INNER JOIN (
    SELECT
        Age,
        DepartmentID,
        MIN(EmployeeID) AS min_id
    FROM
        [dbo].[Employee]
    GROUP BY
        Age, DepartmentID
) T2
    ON T1.EmployeeID = T2.min_id;

Method 8. Using INTERSECT
In SQL Server, using INTERSECT in place of DISTINCT is also an option to get unique records.

Syntax
SELECT <column1>, <column2>
FROM <Table_name>
INTERSECT
SELECT <column1>, <column2>
FROM <Table_name>


Example

SELECT Age, DepartmentID
FROM [dbo].[Employee]
INTERSECT
SELECT Age, DepartmentID
FROM [dbo].[Employee]

Method 9. Using UNION
In SQL Server, using UNION in place of DISTINCT is also an option to get unique records.


Syntax
SELECT <column1>, <column2>
FROM <Table_Name>
UNION
SELECT <column1>, <column2>
FROM <Table_Name>

Example
SELECT Age, DepartmentID
FROM [dbo].[Employee]
UNION
SELECT Age, DepartmentID
FROM [dbo].[Employee];

HostForLIFEASP.NET SQL Server 2022 Hosting

 



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in