Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clustered index on two columns

I've a many-to-many table, let's say:

PersonJob(personId,jobId)

with clustered index (personId,jobId).

The question is:

If somewhere in SQL I'll make a query like:

SELECT *
FROM PersonJob JOIN Job ON PersonJob.jobId = Job.jobId
.......

will it take advantage of that clustered index to find records with particular jobId in PersonJob table ? Or I would be better of creating new non-clusterd non-unique index on jobId column in PersonJob table?

Thanks Pawel

like image 407
dragonfly Avatar asked Mar 25 '11 08:03

dragonfly


People also ask

Can a clustered index be on multiple columns?

Short: Although SQL Server allows us to add up to 16 columns to the clustered index key, with maximum key size of 900 bytes, the typical clustered index key is much smaller than what is allowed, with as few columns as possible.

How do I create a clustered index in multiple columns?

SQL Server CREATE CLUSTERED INDEX syntax First, specify the name of the clustered index after the CREATE CLUSTERED INDEX clause. Second, specify the schema and table name on which you want to create the index. Third, list one or more columns included in the index.

Can we create clustered index with included columns?

If yes then how does it work internally? As per my understanding the leaf level of the clustered index are the actual data pages itself, and it stores entire row include with the key column (on which index is created). By definition a clustered index includes all columns... so there are none left to include.

Can you cluster two indexes?

Clustered Index. A clustered index is an index which defines the physical order in which table records are stored in a database. Since there can be only one way in which records are physically stored in a database table, there can be only one clustered index per table.


1 Answers

You will not have any advantage from the clustered index and your query would still need to scan all rows of the PersonJob table.

If the columns were reversed in your clustered index (jobID, personId) then you would take advantage of the index. Consider that a clustered index sorts the actual rows in your table by the values of the columns that form the index. So with a clustered index on (personId, jobID) you have all the rows with the same personId "grouped" together (in order of jobID), but the rows with the same jobID are still scattered around the table.

like image 153
Paolo Falabella Avatar answered Oct 13 '22 17:10

Paolo Falabella