I need help understanding how to create indexes. I have a table that looks like this
My query looks like this:
SELECT *
FROM table1
WHERE name = 'sam'
What if the query has a order by statement?
SELECT * FROM table1 WHERE name = 'sam' ORDER BY id DESC
What if I have 2 parameters in my where statement?
SELECT * FROM table1 WHERE name = 'sam' AND age > 12
The correct way to create an index with included columns? Either via Management Studio/Toad/etc, or SQL ( documentation ):
CREATE INDEX idx_table_1 ON db.table_1 (name) INCLUDE (id)
ORDER BY
The ORDER BY
can use indexes, if the optimizer sees fit to (determined by table statistics & query). It's up to you to test if a composite index or an index with INCLUDE
columns works best by reviewing the query cost.
If id
is the clustered key (not always the primary key though), I probably wouldn't INCLUDE the column...
Same as above - you need to test what works best for your query. Might be composite, or include, or separate indexes.
But keep in mind that:
I highly recommend reading Kimberly Tripp's " The Tipping Point " for a better understanding of index decisions and impacts.
Since I do not know which exactly tasks your DB is going to implement and how many records in it, I would suggest that you take a look at the Index Basics MSDN article. It will allow you to decide yourself which indexes to create.
If ID
is your primary and/or clustered index key, just create an index on Name, Age
. This will cover all three queries.
Included fields are best used to retrieve row-level values for columns that are not in the filter list, or to retrieve aggregate values where the sorted field is in the GROUP BY
clause.
If inserts are rare, create as much indexes as You want.
For first query create index for name column.
Id column I think already is primary key...
Create 2nd index with name and age. You can keep only one index: 'name, ag'e and it will not be much slower for 1st query.
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.