SQL Server 2014 is shipped with lots of exciting features and enhancements, which I usually share with you in my blog from time to time. Today, I will discuss a new enhancement that will minimize your code. This enhancement is actually in the CREATE TABLE (Transact-SQL). Now you can actually create NONCLUSTERED index within the create statement and you do not need to alter table to add NONCLUSTERED index anymore. However, if you want to follow the old method, you can continue doing it. The old method has NOT been discontinued.
Given below are both methods, demonstrating the enhancement.
NEW Method : (Create NONCLUSTERED index within the create table statement)
In this method, we will create NONCLUSTERED index within create table statement. This script is compatible with SQL SERVER 2014 and above.
USE AdventureWorks2014 GO --DROP TABLE Employee --GO CREATE TABLE Employee ( [Emp_ID] int NOT NULL, [LastName] varchar(255) NOT NULL, [FirstName] varchar(255), [Address] varchar(255), [City] varchar(255), [PostalCode] nvarchar(15), CONSTRAINT pk_Emp_ID PRIMARY KEY ([Emp_ID]), INDEX IX_Employee_PostalCode NONCLUSTERED (PostalCode) ); GO --OUTPUT
OLD Method : (Create NONCLUSTERED index after creation of the table)
In this method, we will create NONCLUSTERED index AFTER table creation. This script is compatible with SQL SERVER 2005 and above.
USE AdventureWorks2012 GO --DROP TABLE Employee --GO CREATE TABLE Employee ( [Emp_ID] int NOT NULL, [LastName] varchar(255) NOT NULL, [FirstName] varchar(255), [Address] varchar(255), [City] varchar(255), [PostalCode] nvarchar(15), CONSTRAINT pk_Emp_ID PRIMARY KEY ([Emp_ID]) ) GO CREATE NONCLUSTERED INDEX IX_Employee_PostalCode ON dbo.Employee (PostalCode) GO
Conclusion
As you can see above, both methods will give you the same output, however, new method will reduce the line of code. Let me know your feedback about new enhancement.
Leave a Reply