I have a simple business requirement. Our users want to be able to click a button and have it take them to the next customer, alphabetically. So I know the current customer's name. What is the most efficient SQL I can write that gets me only the NEXT customer, alphabetically, by name? Somehow
Select * from Customer where name > 'currentname' order by name
and then picking off the first row doesn't seem right to me. There are 100,000+ customers in the database. All help appreciated!
You're right, returning thousands of records just to pick off the first one is grossly inefficient. You need to return just one.
If you're using SQL/Server or Access, you can use the TOP keyword --
select top 1 * from Customer where name > 'currentname' order by name
If you're running MySQL, use LIMIT instead of TOP --
select * from Customer where name > 'currentname' order by name limit 1
With TOP or LIMIT, the optimizer should be smart enough simply to retrieve the desired record directly, assuming there's an index on the name. That's quite important, because without that index, the entire table will have to be scanned and all higher names sorted. And that's inefficient, even if it returns only one record.
If your database does not support TOP or LIMIT, try --
select * from Customer where name = ( select min(name) from Customer where name > 'currentname' )
This also returns just one record, but again, it will be efficient only if that index on name has been declared.
By the way, none of the above solutions will return anything if you happen to be sitting on the highest name in the table. You'll need to take care of this situation in your application, perhaps by "greying out" or inactivating the Next button or link.
For More Information
- What do you think about this answer? E-mail the edtiors at editor@searchDatabase.com with your feedback.
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.
Dig Deeper on Oracle and SQL
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.