tags:

views:

287

answers:

1

Dear all,

I doubt on the speed and result of below queries. Could anyone give me the explanation on them? (These queries written for Oracle database)

Let say I have a table table1(ID, itemID, trnx_date, balance, ...). I want to get the latest balance of an item.

Query 1:

SELECT balance FROM table1 WHERE ID = (SELECT MAX(ID) from table1 WHERE itemID = *item_id*);

Query 2:

SELECT balance FROM table1 WHERE itemID = *item_id* AND rownum = 1 ORDER BY ID DESC;

where *item_id* is the variable.

Thus, do these two queries give the same result? And which one is faster or is there any other query that is faster than them?

Thanks

+2  A: 

Rownum in Oracle is calculated before the sort (my mistake earlier, I haven't used Oracle in a bit). So, this query is identical to the first:

SELECT 
    balance
FROM 
    (SELECT balance FROM table1 WHERE itemID = *item_id* ORDER BY ID DESC)
WHERE
    rownum = 1;

In this case, given an index on ID, this may be slightly faster.

Why haven't you just run them yourself to benchmark them?

Eric
Thanks Eric for your answer, but as I know, the process order of select statement is FROM, WHERE, ORDER BY, then SELECT. Thus, when the condition is found so it will stop finding records (because of ROWNUM=1) and then sort the result, so the result will not be the same. I have tested another table data, and the result is different !!!
Sambath