About Me

My photo
I am an MCSE in Data Management and Analytics, specializing in MS SQL Server, and an MCP in Azure. With over 19+ years of experience in the IT industry, I bring expertise in data management, Azure Cloud, Data Center Migration, Infrastructure Architecture planning, as well as Virtualization and automation. I have a deep passion for driving innovation through infrastructure automation, particularly using Terraform for efficient provisioning. If you're looking for guidance on automating your infrastructure or have questions about Azure, SQL Server, or cloud migration, feel free to reach out. I often write to capture my own experiences and insights for future reference, but I hope that sharing these experiences through my blog will help others on their journey as well. Thank you for reading!

How to Create a Nonclustered Index in SQL Server?

 

How to Create a Nonclustered Index in SQL Server?

In your HumanResources.Department table, you already have a Clustered Index on DepartmentID because it is the Primary Key. Now, let’s create a Nonclustered Index on another column to speed up queries.


🔹 Syntax to Create a Nonclustered Index

To create a Nonclustered Index, use the following command:

CREATE NONCLUSTERED INDEX IX_Department_DepartmentName  
ON HumanResources.Department (DepartmentName);

✔ This creates a Nonclustered Index on DepartmentName.
✔ It helps queries that filter or sort by DepartmentName to execute faster.


🔹 Creating a Nonclustered Index on Multiple Columns

You can create a composite index (index on multiple columns) to speed up queries that involve multiple columns.

CREATE NONCLUSTERED INDEX IX_Department_DepartmentName_Location  
ON HumanResources.Department (DepartmentName, Location);

✔ Useful if queries frequently filter using both DepartmentName and Location.


🔍 Checking If the Index Exists

After creating the index, verify it using:

SELECT * FROM sys.indexes  
WHERE object_id = OBJECT_ID('HumanResources.Department');

🔄 When Should You Use a Nonclustered Index?

Use a Nonclustered Index when: ✔ Queries filter or sort by a column frequently.
✔ The column is not part of the Primary Key (because the Primary Key is already a Clustered Index).
✔ Queries return a small subset of rows, not the entire table.


📝 Summary

CREATE NONCLUSTERED INDEX is used to create a nonclustered index.
✔ Nonclustered Indexes improve search performance on frequently used columns.
✔ Use Composite Indexes if multiple columns are used together in queries.

Would you like help analyzing which columns need indexing? 😊

No comments: