Click here to Skip to main content
15,881,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Table " Ledger" is having huge number of records.
Account ID is FK (not indexed),
ID is PK

which one is the best way to get faster result?
Its taking 00:00:01 seconds for both query

SQL
SELECT TOP 1 OpeningBal FROM Ledger
WHERE AccountID=123456 
ORDER BY ID DESC 

OR
SQL
SELECT OpeningBal FROM Ledger
 WHERE ID = (SELECT MAX(ID) FROM Ledger WHERE AccountID=123456 );


What I have tried:

SQL
SELECT TOP 1 OpeningBal FROM Ledger
WHERE AccountID=123456 
ORDER BY ID DESC 

AND
SQL
SELECT OpeningBal FROM Ledger
 WHERE ID = (SELECT MAX(ID) FROM Ledger WHERE AccountID=123456 );
Posted
Updated 23-Nov-17 23:50pm
Comments
Santosh kumar Pithani 9-Nov-17 1:14am    
"SET STATISTICS IO ON ;SET STATISTICS TIME ON " which were help you to find out which query is taking less time CPU time and elapsed time.
Sadique KT 9-Nov-17 1:47am    
Thanks... that's given the idea..
Santosh kumar Pithani 9-Nov-17 2:05am    
Welcome

1 solution

actually first one is the best

SELECT TOP 1 OpeningBal FROM Ledger
WHERE AccountID=123456 
ORDER BY ID DESC 


and yes I would also suggest to

"SET STATISTICS IO ON ;SET STATISTICS TIME ON
 
Share this answer
 
Comments
Sadique KT 24-Nov-17 12:07pm    
Thank you...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900