Reputation:
I have a classified_id
variable which matches one document in a MySql table.
I am currently fetching the information about that one record like this:
SELECT * FROM table WHERE table.classified_id = $classified_id
I wonder if there is a faster approach, for example like this:
SELECT 1 FROM table WHERE table.classified_id = $classified_id
Wont the last one only select 1 record, which is exactly what I need, so that it doesn't have to scan the entire table but instead stops searching for records after 1 is found?
Or am I dreaming this?
Thanks
Upvotes: 1
Views: 163
Reputation: 12704
Why don't you try it?
SELECT 1 FROM table;
returns
+---+
| 1 |
+---+
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
+---+
6 rows in set (0.00 sec)
which is a computed column, a constant value of one in this case (for all 6 rows in my test case).
For your question
SELECT * FROM table WHERE table.classified_id = $classified_id
this is the fastest way to retrieve data (assuming that you need all the columns from the table)
There are following things that you can do:
other then this for such a simple query the only next step would be to partition the table to several hard drives (which might not be an option on your system).
Upvotes: 2
Reputation: 157828
Yes, you're dreaming this.
There are 2 major faults in your reasoning:
Upvotes: 4
Reputation: 2636
You should add an index to the classified_id column to avoid a table scan.
CREATE INDEX classified_idx ON table (classified_id);
Upvotes: 2
Reputation: 219794
You want to use LIMIT
:
SELECT * FROM table WHERE table.classified_id = $classified_id LIMIT 1
Upvotes: 6