Clarification of MySQL index required to be "spanning" of all "and groups" - mysql

From the MySQL documentation here
Any index that does not span all AND levels in the WHERE clause is not used to optimize the query. In other words, to be able to use an index, a prefix of the index must be used in every AND group.
What exactly does this mean? Does it mean that for an index to be used, that every component of the AND query must refer to that index?
So lets say we have a Person table with SID (primary), first_name (index), last_name.
Does that mean that for the following query
Select * from Person where first_name='foo' and last_name='bar'
will not use the index on first_name?

An AND group is a set of comparisons that are combined with AND. A WHERE clause has multiple AND groups if it uses OR to combine several of these, e.g.
WHERE (col1 = 1 AND col2 = 2 AND col6 = 10) OR (col1 = '5' AND col4 = 'B' AND col2 = 16)
has two AND groups. There's one group that tests col1, col2, and col6, and another group that tests col1, col4, and col2.
So an index can be used if it has a prefix that's tested in every one of these groups. For instance, an index on (col1, col2, col3) could be used because the prefix (col1, col2) spans both groups.

That statement in the document is rather misleading. It seems to contradict directly with the first example given under that statement.
The following WHERE clauses use indexes:
... WHERE index_part1=1 AND index_part2=2 AND other_column=3
Here it's clearly stated that the index is used even though other_column is not a part of the index. The confusion then, is caused by what exactly is an 'AND Group'. Bamar has explained that really well in his answer so I will not go into that here. But suffice to say
Select * from Person where first_name='foo' and last_name='bar'
Will user an index provided that number of rows with first_name = 'foo' is much smaller than total number of rows in the table.

The statement you quoted here is referring to the multiple column indexing or compound indexes.
It indicates that if you have created an index on multiple columns, they all should be presented in the same order in and groups.
If you have crested an index on col1, col2, col3
And groups can be
col1=1 and col2=2 and col3=3
You can also have
col1=1 and col2=2
But you cannot have
col2=1 and col3=3
Because it is not the prefix of the index

Related

How to create Multiple-Column Indexes efficiently?

Let's say I've coded.
create index use_index on tbl_nm (col2 ,col3 ,col4 ,col5);
would use_index be used in
select * from tbl_nm where col2="something", col5 = "something", col3="something");
Also, we should have created index by ordering the most unique on the left and the most common on the right. right?
And if I would like to order the query result should I add that column into the index too?
The index should be at least refs used in common queries first followed by columns search by range.
So in your example here col2 and col3 will be use this index. but because there is no col4, the searching for col5 won't be as quick. i.e. all col4 items with col2 and col3 matching "something" will be scanned for a matching col5.
If you where searching for col4 rather than col5, it would be a binary search to the required item.
Use EXPLAIN {query} to show what the index usage is.
Consideration of most unique vs least in the order of the index isn't really considered.

single-column or composite index

For a table like this
[ col1 - col2 - col3 - col4 ]
[ 1 - 2 - 3 - 4 ]
I'm going to use two types of queries in two cases
One is SELECT * FROM table WHERE col1 = 1 AND col2 = 2 AND col3 = 3;
Another is SELECT * FROM table WHERE col1 = 1 AND col2 = 2 AND col4 = 4;
In this case, Do I make a
composite index for col1 AND col2 only and a single-column index for col3 AND col4
or do I go
ALL columns single-column index
or put
ALL the columns in composite index
Side question: Do I have to name the Index? And what is the Index size?
Have these two:
INDEX col123 (col1, col2, col3),
INDEX col214 (col2, col1, col4)
Notes:
For the 2 queries given, it does not matter which order the 3 columns are in the composite queries.
I did col1 and col2 in different orders just in case some other query needs col2 without col1.
Having INDEX(col3) (single-column) is less useful.
With INDEX(col1, col2), INDEX(col3) -- The optimizer will pick one index and not use the other. This is less good than having an index with all three columns.
Luke is good; my index cookbook might be better?
The "rules of thumb" are aimed at Postgres. Do not use them; there are too many things that are incorrect for MySQL.
The "query tuning" link is aimed at DB2; it mostly applies to MySQL.
INSERTs do take a little time to update the index(es), but most of that work is delayed (see "Change buffering") for non-UNIQUE indexes. Don't let that stop you from adding an index. The benefit on a SELECT usually far outweighs the cost in INSERT.
Index names are optional in MySQL, but the default for a composite index can be misleading.
Another way to compare queries and/or indexes, even with too few rows to get reliable timings:
FLUSH STATUS;
SELECT ...;
SHOW SESSION STATUS LIKE 'Handler%';
Big numbers = bad; small numbers = smile.
A compound index on col1 and col2, with single-column indexes on col3 and col4 is probably going to work best. But the way to tell for certain is to build a table for testing, and populate it with sample data. If possible, insert roughly the same amount of data you expect in production.
Then build indexes, run the queries, and read the execution plans. Drop the indexes, build them a different way, run the queries, and read the execution plans.
You should also think about what other queries need to use this table, and how indexes affect those queries. Think about INSERT and DELETE queries as well as SELECT statements.
Whether you have to name the index depends on the dbms. Most of them will supply a system-generated name if you leave it out. The size of the index depends on the dbms; there's usually a way to figure it out if the dbms doesn't supply explicit functions or stored procedures to do that.

Unique first column in multi-column index

I have multi-column index for 2 columns. Can I make first column unique without making separate index for that?
If I understand correctly mysql can use only first column in this index for lookups, so can it use it to detect uniqueness?
The short answer is "No". Because it doesn't make much sense.
Indeed, MySQL is able to use a multiple-column index for operations that use only the leftmost "n" columns from the index definition.
Let's say you have an index on columns (col1, col2). MySQL can use it to find records matching conditions on both col1 and col2, GROUP BY col1, col2 or ORDER BY col1, col2. It is important to notice that col1 and col2 needs to used in this order in the GROUP BY or ORDER BY clause. Their order doesn't matter on WHERE or ON clauses as long as both are used.
MySQL can also use the same index for WHERE or ON conditions and GROUP BY or ORDER BY clauses that contain only col1. It cannot, however, use the index if col2 appears without col1.
What happens when you have an index on columns (col1, col2) and all the rows have distinct values in column col1?
Let's assume we have a table that have distinct values in column col1 and it has an index on columns (col1, col2). When MySQL needs to find the rows that match WHERE col1 = val1 AND col2 = val2, by consulting the index it can find the row that have col1 = val1. It doesn't need to use the index to refine the list of candidate rows because there is no list: there is at most one row having col1 = val1.
Sure, most of the times MySQL will use the index to check if col2 = val2 but having col2 in this index doesn't bring more useful information to the index. The storage space it takes and the processing power it uses on table data updates are too big for the tiny contribution it adds to rows searching.
The whole purpose of having indexes on multiple columns is to help searching by shrinking the list of matching rows for a given set of values when the columns included in a multiple-column index cannot be used individually because they don't contain enough distinct values.
Technically speaking, there is no way to tell MySQL you want to have a multiple-column index on (col1, col2) that must have unique values on col1. Create an UNIQUE INDEX on col1 instead. Then think about the data you have in the table and the queries you run against it and decide if another index on col2 only isn't better than the multiple-column index on (col1, col2).
In order to decide you can create the new indexes (UNIQUE on col1, INDEX on col2), put EXPLAIN in front of the most frequent queries you run on the table and check what index will pick MySQL up for use.
You need to have enough data (thousands of rows, at least, more is better) in the table to get accurate results.
You asked.
I have multi-column index for 2 columns. Can I make first column unique without making separate index for that?
The answer is no. You need a separate unique index on the first column to enforce a uniqueness constraint.

Would WHERE col1 and ORDER BY col2 use a composite key on (col1,col2)?

I have a database table (potentially huge, with hundreds of millions of records in the future) on which I would execute the following query very often:
select *
from table1
where col1 = [some number]
order by col2
Obviously having an index on "col1" would make it run fast. col1 is not unique, so many rows (2000+ I expect) would be returned.
Does it make sense to create an index on (col1, col2)? Would MySQL use it for this query?
Also, if I just query without "order by" part, would this index be used as well for the "where" part?
Yes, it will help, mysql will use composite index with first part on WHERE and second part on ORDER BY. You can read about ORDER BY optimization here: http://dev.mysql.com/doc/refman/5.5/en/order-by-optimization.html

MySQL indices and order

This is a question that I've had forever.
As far as I know the order of indices matter. So an index like [first_name, last_name] is not the same as [last_name, first_name], right?
If I only define the first index, does it mean that it will only used for
SELECT * FROM table WHERE first_name="john" AND last_name="doe";
and not for
SELECT * FROM table WHERE last_name="doe" AND first_name="john";
Since I am using a ORM, I have no idea in which order these columns are going to be called. Does that mean that I have to add indices on all permutations? That is doable if I have a 2 column index, but what happens if my index is on 3 or 4 columns?
Index order matters when your query conditions only apply to PART of the index. Consider:
SELECT * FROM table WHERE first_name="john" AND last_name="doe"
SELECT * FROM table WHERE first_name="john"
SELECT * FROM table WHERE last_name="doe"
If your index is (first_name, last_name) queries 1 and 2 will use it, query #3 won't.
If your index is (last_name, first_name) queries 1 and 3 will use it, query #2 won't. Changing the condition order within WHERE clause has no effect in either case.
Details are here
Update:
In case the above is not clear - MySQL can only use an index if the columns in query conditions form a leftmost prefix of the index. Query #2 above can not use (last_name, first_name) index because it's only based on first_name and first_name is NOT the leftmost prefix of the (last_name, first_name) index.
The order of conditions WITHIN the query does not matter; query #1 above will be able to use (last_name, first_name) index just fine because its conditions are first_name and last_name and, taken together, they DO form a leftmost prefix of (last_name, first_name) index.
ChssPly76 is correct that the order of boolean expressions does not have to match the order of columns in the index. Boolean operators are commutative, and the MySQL optimizer is smart enough to know how to match the expression to the index in most cases.
I also want to add that you should learn how to use the EXPLAIN feature of MySQL so you can see for yourself which indexes the optimizer will choose for a given query.
Why not to extend the answer a little bit to make completely everything crystal clear at once.
If the table has a multiple-column index, any leftmost prefix of the index can be used by the optimizer to find rows. For example, if you have a three-column index on (col1, col2, col3), you have indexed search capabilities on (col1), (col1, col2), and (col1, col2, col3).
MySQL cannot use an index if the columns do not form a leftmost prefix of the index. Suppose that you have the SELECT statements shown here:
SELECT * FROM tbl_name WHERE col1=val1;
SELECT * FROM tbl_name WHERE col1=val1 AND col2=val2;
SELECT * FROM tbl_name WHERE col2=val2;
SELECT * FROM tbl_name WHERE col2=val2 AND col3=val3;
If an index exists on (col1, col2, col3), only the first two queries use the index. The third and fourth queries do involve indexed columns, but (col2) and (col2, col3) are not leftmost prefixes of (col1, col2, col3). - MySQL dev