MySql Table Index

Indexes are used to find rows with specific column values faster.
without an index MYSQL has to start with the first record and then read through the whole table to find the relevant rows. if the table is larger then it costs performance.
If index is defined on a table column (e.g named mtype in module table), then mysql will determine the postion in the middle of the data file accroding to your where clause in query, insted of looking at the whole data file.
PRIMARY KEY, UNIQUE, INDEX, and FULLTEXT are the indexes mostly used in mysql.
In general indexes are used
  • To quickly find the rows that match a WHERE clause
  • To eliminate rows from consideration. If there is a choice between multiple indexes, MySQL normally uses the index that finds the smallest number of rows.
  • example
      mysql> SELECT * FROM tbl_name WHERE col1=val1 AND col2=val2;
      If a multiple-column index exists on col1 and col2, the appropriate rows can be fetched directly. If separate single-column indexes exist on col1 and col2, the optimizer tries to find the most restrictive index by deciding which index will find fewer rows and using that index to fetch the rows.
  • If the table has a multiple-column index, any leftmost prefix of the index can be used by the optimizer to find rows.
  • e.g
    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 can’t use a partial index if the columns don’t 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 col2=val2;
    SELECT * FROM tbl_name WHERE col2=val2 AND col3=val3;

    If an index exists on (col1, col2, col3), only the first of the preceding queries uses the index. The second and third queries do involve indexed columns, but (col2) and (col2, col3) are not leftmost prefixes of (col1, col2, col3).
    The following SELECT statements will not use indexes:
    SELECT * FROM tbl_name WHERE key_col LIKE '%Patrick%';
    SELECT * FROM tbl_name WHERE key_col LIKE other_col;
    In the first statement, the LIKE value begins with a wildcard character. In the second statement, the LIKE value is not a constant.

    Comments

    Popular posts from this blog

    How to call php functions inside smarty template directly

    Top 50 Web Hacking Techniques

    PHP / SQL Security – The Big Picture