# Query Optimization Direction

**URL:** <https://forum.kirupa.com/t/query-optimization-direction/269623>\
**Category:** programming\
**Created:** [August 29, 2008, 6:08pm UTC](https://forum.kirupa.com/t/query-optimization-direction/269623 "2008-08-29T18:08:54Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![tomazws](https://avatars.discourse-cdn.com/v4/letter/t/46a35a/32.png) [@tomazws](https://forum.kirupa.com/u/tomazws)\
**Post date:** [August 29, 2008, 6:08pm UTC](https://forum.kirupa.com/t/query-optimization-direction/269623/1 "2008-08-29T18:08:54Z")

</div>

Hi, I have a 6000-row table for “products”. Let’s say I need to select the latest 30 rows to display on the website, the simple query would look like this right?

```auto
SELECT * FROM products ORDER BY id DESC LIMIT 30

```

In phpMyAdmin, it shows that query took 0.0039 sec. Though, if I do an “EXPLAIN”, it shows that it is scanning through all 6000 rows in the table:

```auto

id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
1 | SIMPLE | products | index | NULL | PRIMARY | 4 | NULL | 6908 | 	 

```

For the sake of server memory concern (I’m getting numerous warnings from hosting company regarding memory issues), I’ve try to find a better way to do queries, and I’m not sure if I am heading the right direction or not, I came across creating the follow:

```auto

SELECT * FROM products
WHERE id > ((SELECT MAX(id) AS FROM products) - 30)
ORDER BY id DESC

```

It does the exact SAME thing as the short query above, except the query is reference off an indexed column. Though, in phpMyAdmin, it took 0.0047 sec to complete. Following is the “EXPLAIN”:

```auto

id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
1 | PRIMARY | products | range | PRIMARY | PRIMARY | 4 | NULL | 75 | Using where
2 | SUBQUERY | NULL | NULL | NULL | NULL | NULL | NULL | NULL | Select tables optimized away	 

```

As you can see, the query only scanned 75 rows instead of 6000 rows… but why is it taking longer to complete, is it because of the nested query?

Or the most important question, am I even heading the right direction?
