How to Create Unique Constraint with NULL Columns in SQL
Last Updated :
24 Apr, 2024
In SQL databases, maintaining data integrity is crucial, and one common requirement is applying uniqueness among certain columns. However, handling NULL values in these columns can be challenging. By creating a unique constraint with NULL columns, we can ensure that non-NULL values are unique while allowing multiple rows with NULL values.
In this article, We will explores how to create such a constraint in SQL, ensuring data integrity and consistency in database design and so on.
Create Unique Constraints with NULL Columns in SQL
- A filtered index is a special type of index that only applies to a subset of rows in a table. We can define a filtered index on a column, but specify that NULL values are not included in the index. This way, we can have multiple rows with NULL in that column without violating uniqueness constraints.
- Unique constraints are special rules in SQL databases. They make sure that each row has its values in certain columns. No two rows can have the same values for those columns. This keeps the data unique and helps avoid mistakes.
- When setting up unique constraints, we pick the columns that need to be unique. But columns that allow "NULL" values need extra care. NULLs work differently with unique constraints.
- We must understand how unique constraints work with NULL values. The constraint ensures that non-NULL values are unique. But it allows multiple rows with NULL values in the constrained columns. This means NULL values are considered unique from each other and non-NULL values.
- When creating unique constraints. We need to understand how they impact data integrity and consistency in our database design. Having multiple NULL values may or may not be desired, depending on our requirements.
Prerequisites
- Basic understanding of SQL syntax and database management.
- Familiarity with the concept of indexes and constraints in SQL.
- Understanding of Database Schema: It is important to know the database plan. You must understand the tables and columns. This will help enforce uniqueness. The tables and columns must be clear. You should know which columns need uniqueness.
- Knowledge of NULL Values: We should know how NULL acts in SQL. NULL items are not the same as each other in most SQL programs. Two NULL things are not equal or the same.
- Access and Permissions: Before making any changes to the database schema, it's crucial to verify your access rights and permissions. You must have the necessary authority to create or modify constraints within the database system. Failing to secure the appropriate permissions could result in unauthorized and potentially damaging alterations.
- Database Engine Support: Verify that your database engine supports the creation of unique constraints with NULL columns. Most SQL databases can do this. But, you should check if you use a different database. It is a standard feature.
Example of Create unique constraint with NULL columns in SQL
Suppose we have a table named "employees" with the following structure:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100) UNIQUE
);
Now, imagine you want to change this table. You want only one email for each row. But you also want to let some rows have no email.
Step 1: Alter the Table
ALTER TABLE employees
ADD CONSTRAINT unique_email UNIQUE (email);
This SQL statement adds a unique constraint named unique_email on the email column of the employees table.
tableStep 2: Test with Data
Let's insert some sample data into the employees table to test the unique constraint:
INSERT INTO employees (employee_id, first_name, last_name, email)
VALUES
(1, 'John', 'Doe', '[email protected]'),
(2, 'Jane', 'Smith', NULL),
(3, 'Michael', 'Johnson', NULL);
In this data insertion, we have two employees with NULL values in the email column.
Inserting values in table with "NULL" value.Step 3: Validate the Constraint
INSERT INTO employees (employee_id, first_name, last_name, email)
VALUES
(4, 'Emily', 'Davis', '[email protected]');
You cannot save this email address here. This is not allowed. You must give a new email address. The email address you typed is already used. Each email address must be different. The system does not let you use.
Inserting same email in different columnThis lead to an error:
Error Code: 1062. Duplicate entry '[email protected]' for key 'employees.email'

Step 4: Verify NULL Behavior
Now, let's check if the unique constraint allows NULL values:
INSERT INTO employees (employee_id, first_name, last_name, email)
VALUES
(5, 'Chris', 'Anderson', NULL);
This insertion should succeed because NULL values are treated as distinct, and the constraint only enforces uniqueness on non-NULL values.
Insertion of Null valueBy following these steps, you can create a unique constraint with NULL columns in SQL and ensure data integrity while allowing flexibility for NULL values.
Conclusion
Overall, Ensuring uniqueness in a SQL database can be tricky when dealing with NULL values. Traditionally, NULL values are treated as distinct from each other, which can lead to multiple rows with NULL entries being allowed, even if uniqueness is enforced on that column. However, there are two main approaches to overcome this challenge and maintain data integrity while accommodating NULL values where uniqueness is desired. The first approach involves utilizing filtered indexes, which are indexes that consider only a subset of rows based on a specified condition.
Similar Reads
Create Unique Constraint with NULL Columns in MySQL
Unique constraint in MySQL ensures that each value in the column is unique. If a column contains a NULL value, it is also treated as a unique value, but if a column contains multiple NULL values it can not have a unique constraint.In this article we will look over how we can Create unique constraint
3 min read
How to Efficiently Convert Rows to Columns in SQL?
In SQL, rows and columns are the fundamental building blocks of a database. Rows represent individual records, while columns represent the attributes or characteristics of those records. However, there may be instances where we need to convert rows to columns in order to better analyze and manipulat
5 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, cons
2 min read
How to Filter Rows Without Null in a Column in SQL?
Here we will see, how to filter rows without null in a column of an MS SQL Server's database table with the help of a SQL query using IS NOT NULL operator. For the purpose of demonstration, we will be creating a demo_orders table in a database called âgeeksâ. Creating the Database: Use the below SQL
2 min read
How to Count Distinct Values in PL/SQL?
PL/SQL, an extension of SQL for Oracle databases, allows developers to blend procedural constructs like conditions and loops with the power of SQL. It supports exception handling for runtime errors and enables the declaration of variables, constants, procedures, functions, packages, triggers, and mo
5 min read
How to SELECT DISTINCT on Multiple Columns in SQL?
In the world of databases, data duplication can lead to confusion and inefficiency. SQL provides a powerful tool, SELECT DISTINCT, to retrieve unique values from columns. However, when dealing with multiple columns, the approach becomes more detailed. In this article, we will explain how to use SELE
4 min read
How to SELECT DISTINCT on Multiple Columns in SQLite?
SQLite is a lightweight and server-less relational database management system (R.D.B.M.S). It is a self-contained database and requires very minimal configuration. It is a server-less architecture that is good for mobile applications and simple desktop applications. In this article, we are going to
4 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
2 min read
How to Create id With AUTO_INCREMENT in PL/SQL?
PL/SQL, short for Procedural Language/Structured Query Language, combines SQL capabilities with procedural programming. It supports variable declaration, control flow structures, functions, records, cursors, procedures, and triggers.PL/SQL features a block structure with optional sections for variab
5 min read
How to Count Unique and Distinct Values in Excel
Counting unique values in Excel is a common challenge when working with large datasets, especially for those analyzing data or generating reports. Knowing how to count distinct Excel values accurately is crucial when managing data like customer lists, product inventories, or sales records. This arti
15 min read