简体   繁体   中英

Best way to create SQL indices?

What is the best way to create an SQL index in SQL database?

CREATE INDEX idx ON sometable (col1, col2, col3);

Or

CREATE INDEX idx1 ON sometable (col1);
CREATE INDEX idx2 ON sometable (col2);
CREATE INDEX idx3 ON sometable (col3);

Which is the difference between these 2 methods? Does it depends on the SQL implementation? (SQLite, MySQL, MSSQL, ...)? Are there any efficiency considerations when using one of the two methods?

CREATE INDEX idx ON sometable (col1, col2, col3);

This will create a single index on all three fields together. This is perfect, if your queries will use all three fields for their WHERE clause most of the time:

SELECT (fields) FROM Table WHERE col1 = 1 AND col2 = 2 AND col3 = 3

This composite index will also be used when you query on col1 and col2 alone:

SELECT (fields) FROM Table WHERE col1 = 1 AND col2 = 2 

but it cannot be used if you query on either col2 or col3 separately, or on col2 and col3 together:

SELECT (fields) FROM Table WHERE col2 = 2 AND col3 = 3  -- will *NOT* use index
SELECT (fields) FROM Table WHERE col2 = 2               -- will *NOT* use index
SELECT (fields) FROM Table WHERE col3 = 3               -- will *NOT* use index

On the other hand, if you use:

CREATE INDEX idx1 ON sometable (col1);
CREATE INDEX idx2 ON sometable (col2);
CREATE INDEX idx3 ON sometable (col3);

then you create three separate, individual indices on each of the fields. In this case, any query that uses just one of the columns will benefit from that column's index:

SELECT (fields) FROM Table WHERE col1 = 1   -- will use index on col1
SELECT (fields) FROM Table WHERE col2 = 2   -- will use index on col2
SELECT (fields) FROM Table WHERE col3 = 3   -- will use index on col3

however, if you query by two or all three columns together in a single query:

SELECT (fields) FROM Table WHERE col1 = 1 AND col2 = 2 AND col3 = 3

then only one of the three indices created will be used, and it will most likely be less efficient than a composite index on (col1, col2, col3) would be.

So yes, there's definitely a difference in how you create those indices, but there's no single "best way" to do this indexing. It really all depends on how you query your data as to which of the two options is the "better" one in your case.

The first one creates a composite index on 3 columns, whereas the second one creates a simple index on each column. Check out the explanation and examples in the MSDN article .

(See the examples section first and then go and read the definitions of each type of index, otherwise I feel the article is too intimidating)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM