How To Use MySQL Indexes Properly? - mysql

I'm using php and MySQL with a rather large MySQL database and I am trying to use idexes for the first time. I get the concept that the server will look through the index first but I'm moving trouble getting the server to use the index. So my questions are:
Does having a primary key (thus primary index?) in the table get used over the index I'm trying to use from another column? Do I have to explicitly specify the index in the select query? (I'm using several table joins, btw)
Does anyone know of a good beginners guide to using MySQL indexes? I haven't found a good one!

An important rule for mysql indexes, say you have the following index:
KEY(A,B,C)
Then in your code you have a where clause or join such as:
WHERE B = 'mydata' AND C = 'moredata'
Mysql will not be able to make use of the index for the query because the indexes work in the order given and the column A has not been included.
The fix is to either use A in the query or re-order the index (or add a second index) as so:
KEY(C,B,A)
or (if you don`t need A at all in the WHERE/JOIN):
KEY(C,B)
Also check out explain which should help you find why your indexes are not being used.

Related

Adding the same (separate) index to all tables in a schema

I have a schema that is used to archive a data set on a daily basis. Some of the analysis needs to look back, so to optimise things I need to create a couple of indexes on each table. These would be seperate (I'm not trying to cross index or anything) just a simple non-unique index, but on each table in the schema.
The archive has already been building for over a year, so we have some 400 - 500 tables, making a manual ALTER query on each tablea bit too time consuming.
I could write a php script to do it, but wondered if there was a more elegant solution with a single query or transaction?
TIA
I have copied #Shadow's answer in the comments above here to show it as the answer:
Well, the alter table and add index sections will be string constants as you have to generate the alter table statements and then execute the alter table statements you generated in the first step. See an example here: stackoverflow.com/a/44527818/5389997

SQL filtered index not working in MySQL Workbench

Hopefully a very quick question: I'm having some trouble getting the following
index creation statement to work. I'm using MySQL Workbench.
CREATE INDEX HIRE_DATE_INDEX
ON Employee (hiredate)
WHERE hiredate > '2001-01-01';
I'm trying to get the following index creation to work, however regardless of what I look up online the following is listed as the proper syntax but for some reason that is unfathomable at this point, the index is specifically saying that the where clause is in the incorrect place.
I'm clearly missing something in the examples.
(Context, just trying to create a filtered index only interested in dates greater then).
It looks like this should be easy as hell, what am I missing here?
You don't need the WHERE clause. But MySQL doesn't support filtered index. (Reference here)
CREATE INDEX HIRE_DATE_INDEX
ON Employee (hiredate);
Also that command doesn't work if you try to create a primary key. If that's the case, you need to use ALTER TABLE command.

How I can do this in mysql?

I want to make a query that select fields using 'like' but I am not satisfied with the result, for example my register says, "wood table work 45" but if my query is SELECT * FROM schema1.table1 WHERE description LIKE "%table for work%"; returns nothing, I don't want the user need write exactly "table work" or "wood table" to have a result.
Create first a FULL TEXT Index on the column you wants to query this way :
ALTER TABLE `table1`
ADD FULLTEXT INDEX `IndxDescription` (`description`);
You don't need to run an indexer daemon, MySQL does the index / reindex automatically.
FYI: Full-text is supported in InnoDB / MyISAM only in MySQL
reference : http://dev.mysql.com/doc/refman/5.7/en/fulltext-restrictions.html
If you are looking for a more robust solution, consider taking a look on ElasticSearch : https://github.com/elastic/elasticsearch
You might want to look at Natural Language Fulltext search

Is there any disadvantages of unique column in MYSQL

i'd like to ask a question regarding Unique columns in MySQL.
Would like to ask experts on which is a better way to approach this problem, advantages or disadvantages if there is any.
Set a varchar column as unique
Do a SQL INSERT IGNORE
If affected rows > 0 proceed with running the code
versus
Leave a varchar column as not-unique
Do a search query to look for identical value
If there is no rows returned in query, Do a SQL INSERT
proceed with running the code
Neither of the 2 approaches is good.
You don't do INSERT IGNORE nor do you search. The searching part is also unreliable, because it fails at concurrency and compromises the integrity. Imagine this scenario: you and I try to insert the same info into the database. We connect at the same time. Code in question determines that there's no such record in the database, for both of us. We both insert the same data. Now your column isn't unique, therefore we'll end up with 2 records that are the same - your integrity now fails.
What you do is set the column to unique, insert and catch the exception in the language of your choice.
MySQL will fail in case of duplicate record, and any proper db driver for MySQL will interpret this as an exception.
Since you haven't mentioned what the language is, it's difficult to move forward with examples.
Defining a column as an unique index has a few advantages, first of all when you define it as an "unique index" MySQL can optimize your index for unique values (same as a primary key) because mysql doesn't have to check if there are more rows with the same value so it can use an optimized algoritme for the lookups.
Also you are assured that there never will be a double entry in your database instead of handeling this in multiple places in your code.
When you don't define it as UNIQUE you first need to check if an records exists in your table, and then insert something wich requires 2 queries (and even a full table lock) instead of 1 wich decreases your performance and is more error prone
http://dev.mysql.com/doc/refman/5.0/en/constraint-primary-key.html
I'm leaving the fact that you would use the INSERT IGNORE wich IGNORES the exception when the entry allready exists in the database (Still you could use it for high performance operations maybe in some sort of special case). A normal INSERT will give you the feedback if an entry allready exists
Putting a constraint like UNIQUE is better when it comes to query performance and data reliability. But there is also a trade-off when it comes to writing. So It's up to you which do you prefer. But in your case, since you also do INSERT IF NOT EXIST query, so I guess, it's better to just use the Constraint.

How to hint the index to use in a MySQL select query?

I have a MySQL query (running MySQL 5.0.88), which I'm trying to speed up. The underlying table has multiple indices and for the query in question, the wrong index is used (i_active - 16.000 rows, vs. i_iln - 7 rows).
I'm not very experienced with MySQL but read there is a use index hint, which can force mySQL to use a certain index. I'm trying it like this:
SELECT art.firma USE INDEX (i_iln)
...
but this produces a MySQL error.
Question:
Can anyone tell me what I'm doing wrong? (Except running 5.0.88, which I can't change.)
You missed the
FROM table
Correct SQL should be:
SELECT art.firma FROM your_table USE INDEX (i_iln) WHERE ....
select * from table use index (idx);
http://dev.mysql.com/doc/refman/5.0/en/index-hints.html
sometimes, with use index (index_name) optimizer might go for table scan, if you use hint force index, optimizer will be forced to use index, will go for table scan only if no ways left to get the rows with provided index.
SELECT art.firma FROM art FORCE INDEX (i_iln);
for more detail on hints USE INDEX and FORCE INDEX check this link
Select Coloumn1,Coloumn2,Coloumn.... FROM TABLE_NAME USE INDEX(index_name)
WHERE Coloumn="condition";
if you have correct index thn you dnt need to use index(). your query automic select correct index.If your query slow after using index thn recheck your index ,something wrong in index.
thanks in advance.enter code here