Welcome to Appsloveworld Technologies , In the session, we learn about what a unique index is and the difference between a unique index and a unique constraint.
Before continuing with the post, I strongly recommend reading read the previous post of this series.
- How does database indexing work with real time example?
- Clustered and Non clustered index in sql server with real example
what’s a unique index?
A unique index is used to enforce the uniqueness of key values in the index. Let’s understand this with an example.
I have the sample SQL script here, which creates table TblUsers.And if you look at the script, the ID column is marked as a primary key column.
And by default, a primary key constraint creates a unique clustered index on that column if another clustered index doesn’t already exist in the table. Let’s look at this in action.
CREATE TABLE [dbo].[TblUsers](
[Id] [int] Primary Key,
[Name] [nvarchar](100) NULL,
[Email] [nvarchar](100) NOT NULL,
[Gender] [int] NOT NULL,
[RewardsPoint] [decimal](18, 2) NOT NULL
)
Let’s execute the SQL script to create a table, Command completed successfully.
So the table should have been created since we have marked the Id column as the primary key column.
A unique clustered index should have been created on that column for in the table. And obviously, to find that out, we can make use of the system stored procedure,sp_helpindex, passing in the name of the table, which will list all the indexes that are available for this table.
Execute sp_helpindex TblUsers
So let’s execute this. As you can see on the below image we have a unique clustered index on the ID column.
So within the object explorer, refresh the tables folder and you should see the table expand that, expand the index folder and you should see an index that we have just created.
And look at the name it says it’s just a clustered index. It doesn’t tell us whether it’s a unique or non-unique index.
To identify that, you can click on the index, select properties and you should see a unique checkbox checked, which proves that this is a unique clustered index.
How did we get this unique clustered index?
Because we marked the Id column as the primary column. It created this unique clustered index behind the scenes. Since we marked the Id column as a primary key, there should be a primary key as well with that column.
So when I expand the Keys Folder, look at the primary key in the Keys folder. Look at the primary key and look at the index.
They’re actually the same thing, PK__TblUsers and random number.
So in reality, the primary key constraint actually uses a unique index behind the scenes, to enforce, the primary key constraint.
Let’s prove that. Let’s try to drop this index.
And obviously to drop the index we can use the drop index statement drop index. Any time you drop an index you’ll need to specify the table name as well.
Let’s execute the below drop script and see what’s going to happen.
drop index TblUsers.PK__TblUsers__3214EC0799AA7AF9
An explicit drop index is not allowed on this index because it’s being used for primary key constraint enforcement.
So this message proves that the primary key uses a unique index behind the scenes to enforce the constraint.
if you’re not able to drop the index using drop index statement, you can actually do that using the object explorer.
So let’s try to delete this index from the object explorer. Right-click on the index and select delete.
Now refresh the folder, look at what’s happening , the primary key constraint is also gone.
So now if I try to insert duplicates into the table, it will accept the duplicates values.
INSERT [dbo].[TblUsers] ([Id], [Name], [Email], [Gender], [RewardsPoint]) VALUES (1, 'Test 2', 'pankajabcd@gmail.com', 0, CAST(15.00 AS Decimal(18, 2)))
GO
INSERT [dbo].[TblUsers] ([Id], [Name], [Email], [Gender], [RewardsPoint]) VALUES (1, 'Test 3', 'test@test.com', 1, CAST(31685.00 AS Decimal(18, 2)))
INSERT [dbo].[TblUsers] ([Id], [Name], [Email], [Gender], [RewardsPoint]) VALUES (1, 'aakankshi6', 'aakankshi6@gmail.com', 3, CAST(109.00 AS Decimal(18, 2)))
select * from [dbo].[TblUsers]
this proves that behind the scenes, the primary key constraint actually uses a unique index to enforce that constraint.
So the uniqueness of an index is not a separate index by itself. It is just a property of an index. So both a clustered and a non clustered indexes can be unique.
If I want to create a unique non clustered index, for example, let’s say I want to ensure that in tblusers, no two users can have the same name and email.
Let’s say I want to enforce that, I can actually create a unique non clustered index in that case.
Create Unique NonClustered Index UIX_TblUsers_Name_Email
On TblUsers(Name, Email)
So I’m creating a unique non clustered index. And usually, for unique indexes, it’s better if you prefix that with UIX. So just by looking at the name, you can say that this is a unique index on TblUsers on the name and email columns.
Differences between a unique constraint and a unique index
If you want to enforce uniqueness across one or more columns, we will actually use unique key constraint.but now we are talking about using a unique index.
So what’s the difference between them? Actually, there are no major differences between a unique constraint and a unique index.
- when we add a unique constraint, a unique index gets created behind the pictures.
Let’s look at that in action. let’s say I have the table TblCustomers, we just got a Country column on that.
Now I want to ensure that, all countries are unique within the table. How do I do that? I can add a unique constraint. So let’s add a unique constraint. so obviously to add a unique constraint, we have to alter the table.
ALTER TABLE TblCustomers
ADD CONSTRAINT UQ_TblCustomers_Country
UNIQUE NONCLUSTERED (Country)
Let’s execute the command, and refresh the table folder expand the “keys” folder, and then expand the indexes folder.
Now look at this, we have index created and if you look at the type of the index, it’s a non clustered unique index.
If you want to create a clustered index, you can specify that as well
ALTER TABLE TblCustomers
ADD CONSTRAINT UQ_TblCustomers_Country
UNIQUE CLUSTERED (Country)
so whether you add a unique constraint or whether you create an index, there are two ways to create a unique index by adding a unique constraint or using create index statement and directly creating a unique index.
So eventually to actually be creating a unique constraint over a unique index. Now we know that behind the scenes, a unique index gets created. Now you can do that through a constraint or directly using a create index statement.
when do we choose one option over the other?
Now to make our intentions clear, create a unique constraint when data integrity is the objective. this makes the objective of that index very clear.
In either case, this data is validated in the same manner and the query optimizer doesn’t really make any difference between a unique index that you have created by using a constraint or manually created that creates index statement.
Some useful points to remember
- we have already learned that by default, a primary key constraint creates a unique clustered index.
- we have also seen a unique constraint creates a unique non clustered index by default. these are only defaults and they can be changed if we wish to.
The post Sql Server- Difference between unique and non unique index appeared first on Software Development | Programming Tutorials.
Read More Articles
- Linq to SQL Group by and Sum in Select | Linq To SQL Group By and Sum
- How send an HTTP POST request to a server from Excel using VBA?
- What is Difference between where and having clauses in SQL server
- How to Use EXCEPT Operator with an example in Sql
- How to use merge statement in the SQL server
- How to write Re-runnable SQL server query
- How to create Cursor in sql server with example
- How to generate random data in sql server for performance testing
- How to write subquery in select statement in Sql
- How to Log record changes in SQL server in an audit table
- Transfer from one table to another
- SQL Server Query Editors - any that warn of number of rows to be changed?
- How to store decimal values in SQL Server?
- convert string null value to int
- The conversion from varbinary to BLOB is unsupported
- Count distinct values based on criteria in multiple columns
- Get day of week in SQL Server 2005/2008
- SQL Server 2017 installation is stuck
- Presto integration with MSSQL
- T-SQL Stored procedure, declaring variables within the exec
- SQL Server heap v.s. clustered index
- Using TransactionScope in SQL Server 2012
- Can any one simplify this query
- SQL Server 2016 Import Wizard - Trailing Whitespace
- SQL: Update Rows That Are Unique Based on a Column
- TinyTds fails to connect to azure on Debian
- SQLMetal fails to create DBML from SQL Server 2005 database
- Procedure from Firebird to SQL Server
- Hibernate/JPA and MS SQL Server - Open Symmetric Key before DecryptByKey
- SQL Server trigger for update inserted row
- How to test your query first before running it sql server
- how to configure hibernate config file for sql server
- Get Start and End date from multiple rows of dates, excluding weekends
- Lazy loading doesn't work for me inEntity Framework 4
- Convert a date between two dates and times to the first day of a month
- Hibernate foreign key column length mismatch
- Slow loading SQL Server table into pandas DataFrame
- sql server jdbc query on datetime column
- Creating database on remote SQL Server engine
- SQL MAX(COUNT(*)) GROUP BY Alternatives?
- Python: Polling a SQL database every n seconds and executing a task based on it
- SQL Server Service Broker -- Suggestion for Handling Two-Phase Commit Between SQL Server Instances
- Match Columns in Table A to Row Values in Table B to update another Column in Table B
- SQL in one set but not in another
- Inserting data into SQL Server 2014 in C# (Visual 2015) using classes and stored procedure
- German Umlaut hash - SHA256 on SQL server
- getting ddl from database
- Execute a literal string as a SQL statement - placement of single quotes
- SqlDataAdapter Close connection method
- Why is it not practical to show progress for SQL statements?
- SQL query IN clause with very large number of values
- SQL - Search based on type (Int & VarChar)
- The component metadata for "Oracle Destination" could not be upgraded to the newer version of the component
- (SQL) How to select the correct row for each group?
- Why, when I impersonate within a WCF service, can my service not load System.Transactions when I try to run a LINQ to SQL query?
- Using Linq to query linked server in Visual Studio
- Procedure output parameter always returning 0 in sql
- Two visibly identical strings are considered not equal by SQL Server and Excel
- How to check if SQL Server Agent is running
- PK Index Fragmentation on tables with nvarchar primary keys
- How do I convert (shred) arbitrary XML to a flat data structure?
- difference between data in two tables
- sql rowlock on select statement
- SQL Server: multiple INSERT with MERGE
- Copy selected row from datagrid at the end of datagrid
- Dynamically delete the table by using parameter
- Return rows which have same data in three columns
- How to force user to enter value in a database field
- SQL Query to JSON
- SQL Server Compact Edition 4.0 SDK?
- What is the typical usage of View > Server Explorer vs View > SQL Server Object Explorer?
- SQL Server 2019 breaks Base64 encoding as a Scalar-valued Function
- Efficent opening balance calculation in SQL
- What is the quickest way to import 60m records into SQL
- SQL Insert New Column Based on Other Columns and Previous Rows
- sqlserver 2005 Splitting a date range into consecutive years
- Kerberos Double Hop Authentication - SQL Server
- Where are all database file paths stored in SQL?
- How do I write this query more efficiently?
- Select records 1-2 years from begin date
- sql conversions in select statement
- Symfony 2.6 with MSSQL Doctrine failed to update Database
- Search column in database Microsoft sql PHP
- How do I use result of SELECT in one stored procedure in another srored procedure?
- Oracle correlated UPDATE
- Best way in ASP.NET of configuring rows in a database to delete after a certain time
- Can I instruct EF DbContext to use "real" parameter names?
- Subquery Returned More Than 1 Value with the Group By
- SSIS Power Query Source OData Connection Not Working
- OPENROWSET or OPENDATASOURCE Example to get Data from .xlsx or .csv file on file system of Remote Server
- How do you escape double quotes inside a SQL fulltext 'contains' function?
- SQL query to overwrite records
- SQL: create a query with a column identifying each tuple of values
- SQL server: replace characters from string within a specified range
- Entity framework move/archive data from one database to another
- MS SQL - static sql query with dynamic filters
- Does specifying a foreign key make it an index?
- Update one particular cell in MS SQL
- SSAS - OLE DB error in establishing a connection
- Connection to SQL Server through Powershell (not local)
- How to create a time of 9pm today in SQL
- How to Break table column into different columns using Pivot or in any other way
- SQL Server Execution Plans - Actual vs. Estimated
- Different version of ReportViewer component in the same application
- SQL Server where clause using In() vs Wildcard
- Table rows count
- SQL Server convert hexadecimal varchar value to INT
- How can I transform TSQL WHILE EXIST to a more Set based approach?
- SQL - sorting alphanumeric values which are in English and Japanese
- Rotate columns to rows for joined tables
- SSIS Date/Numeric Conversion from Flatfile
- SQL Server 2017 Express Installation fails
- Limit SQL Server column to a list of possible values
- How to alter/create a table which has a column that defaults to a future date's datetimeoffset?
- How to pivot unknown number of columns & no aggregate in SQL Server?
- How to Group by month when there's a turn of the month
- Connect Sql Azure with Android
- How to store image in SQL Server database tables column
- SSIS in SQL Server: How to get it to store password
- sql trigger stopped working after 8 months (not showing up in profiler)
- Invalid column name when using dynamic SQL
- How to set aggregate bit value for a group
- dbo.TempGetStateItemExclusive3 called repeatedly
- Bulk update SQL Server C#
- How to enable/disable trigger in procedure?
- Convert integer to date as MM/DD/YYYY like from 20200926 to 09/26/2020?
- Assigning a 'Y/N' for each StudyId
- How to Stop SSMS 2012 from scripting SPs using sp_executesql
- Join two tables but only get most recent associated record
- Moving and merging reporting server instances
- Setting the value of a column in SQL Server based on the scope_identity() of the insert
- value must exists in both tables
- using pypyodbc to access a table with spaces in its name
- The type of column "" conflicts with the type of other columns specified in the UNPIVOT list - SQL Server 2008
- Trying to add image in SQL Server
- Service Broker / External Application Activation and Visual Studio Debugging
- Preventing inapropriate rows from being inserted into SQL Server database
- Manually insert User in ELMAH
- sql - How can I count the differences of two rows?
- Nhibernate won't delete rows while table has trigger
- The mutator 'modify ()' of '@Mydoc' can not be called with a NULL value
- Convert Rows to Columns based on contents? (PIVOT?)
- Inserting an ID that increments (but is not an AUTOINCREMENT)
- Is there a reason why I shouldn't use NVARCHAR in Sql Server?
- SQL Server - can't do COUNT on DATEDIFF without doing CREATE VIEW
- nvarchar concatenation / index / nvarchar(max) inexplicable behavior
- IIS + Kerberos + SQL Server + EF Initial connection failure
- Wildcard Pattern usage
- What is the use of replication in SQLSERVER2005
- SQL select distinct values in columns / Dynamic value count in columns
- Rails View encoding issue
- Is there a data type in MsSQL bigger than float?
- Restoring a running database in a different name in same server in SQL Server 2012 using Management Studio
- SQL: Query to identify instances of an associated row in one table
- MS Access First function in SQL
- SQL Server: Select rows in table that share value with rows in another table
- SQL-SERVER search array
- linking multiple queues to same service in SQL service broker
- Fastest way to copy sql table
- Python re.findall regex and text processing