1

I have Db of 100,000 users in MYSQL. In that DB i am having column ID,username,Fname,Lname, etc.. When www.example.com/Jim or www.example.com/123 (Where JIM is username and 123 is ID in the users table)

I am using MYSQL query : select * from users where ID = 123 OR username = Jim I am executing above query in PHP. Output of the above query is :

| ID | Username | fname  | lname   |
+----+----------+--------+---------+
|123 |   jim    |  Jim   | Jonson  |

My Problem is its taking huge time to select username or ID in the DB.

I have used following query

SELECT * FROMusersUSE INDEX (UsersIndexId) where id=123

Is this right way to call Index ?

EXPLAIN SELECT * FROM  `users` WHERE ID =327

OP

id  select_type  table    type    possible_keys        key      key_len ref rows Extra 
1     SIMPLE       users  Const  PRIMARY,UsersIndexId  PRIMARY     4   const   

1

Sandeep Kamble
  • 159
  • 1
  • 1
  • 9

2 Answers2

5

I sugest you take a look at this: How MySQL Uses Indexes

Quoting from the first paragraph:

Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times faster than reading sequentially.

That should help speed up your search.

(Edit: Updated the link to a newer version of the SQL docs)

PS: More specifically, column indexes might be what you want. You can find more info about adding indexes here: Create Index Syntax

Kjartan
  • 18,591
  • 15
  • 71
  • 96
2

To complete @Kjartan answer, you can try the following :

ALTER TABLE users ADD INDEX id_i (`ID`);
ALTER TABLE users ADD INDEX username_i (`Username`);

Your queries should be faster.

Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153