SQL Non-Clustered Index Tutorial 🎯

beginner
13 min

SQL Non-Clustered Index Tutorial 🎯

Welcome to our comprehensive guide on SQL Non-Clustered Index! This tutorial is designed for both beginners and intermediate learners, and we'll dive deep into the world of SQL, explaining the concepts from the ground up. Let's get started!

What is a Non-Clustered Index? 📝

A Non-Clustered Index, also known as a non-clustered or secondary index, is a database structure that helps improve the performance of a SQL database by allowing quick access to specific rows in a table based on the indexed columns. It does not change the physical order of the data in the table.

Why Use a Non-Clustered Index? 💡

  1. Improve Query Performance: Non-clustered indexes can help reduce the amount of data that needs to be scanned to retrieve the requested data, making queries faster.

  2. Support for Multiple Columns: Non-clustered indexes can be created on multiple columns, allowing for more specific and efficient querying.

  3. Data Independence: Since the index is separate from the data, changes to the data structure do not affect the index.

Creating a Non-Clustered Index ✅

Let's create a non-clustered index on the "name" column of our "customers" table.

sql
CREATE INDEX idx_customers_name ON customers (name);

Understanding Non-Clustered Index Types 📝

SQL Server supports two types of non-clustered indexes:

  1. Unique Non-Clustered Index: This index ensures that each row in the indexed column is unique.

  2. Non-Unique Non-Clustered Index: This index allows for multiple rows to have the same value in the indexed column.

Non-Clustered Index Key Features 💡

  1. Indexed Columns: Columns that are part of the index are called the indexed columns or key columns.

  2. Fill Factor: This is a percentage that determines the amount of free space left in each page of the index.

  3. Included Columns: These are optional columns that are not part of the indexed key but are included in the index to reduce the number of bookmark lookups.

Querying Non-Clustered Indexes 💡

When you run a SELECT statement with a WHERE clause that uses the indexed column, SQL will use the non-clustered index to find the data quickly.

Practical Example 🎯

Let's create a table, add some data, create a non-clustered index, and query the data using the index.

sql
-- Create a table CREATE TABLE customers ( id INT PRIMARY KEY, name VARCHAR(50), age INT ); -- Insert data INSERT INTO customers (id, name, age) VALUES (1, 'John Doe', 30), (2, 'Jane Smith', 25), (3, 'Mike Johnson', 40); -- Create a non-clustered index CREATE INDEX idx_customers_name ON customers (name); -- Query the data using the index SELECT * FROM customers WHERE name = 'John Doe';

Quiz 🎯

Quick Quiz
Question 1 of 1

What is a Non-Clustered Index in SQL?

Let's continue learning about SQL! 🚀 Stay tuned for more tutorials on CodeYourCraft.