How do I write a query that can return a specific number of rows? Say, base on the constant that I set, I can either return 20 rows, 30 rows from a table (or multiple tables)? Thanks.
If you're using SQL/Server or MS Access, use the TOP keyword --
select top 20 foo, bar from thetable
If you're using MySQL, use the LIMIT keyword --
select foo, bar from thetable limit 20
If you're using Oracle, use ROWNUM or RANK() as explained in "Performing top-N queries in Oracle".
For More Information
- What do you think about this answer? E-mail us at editor@searchDatabase.com with your feedback.
- The Best Microsoft SQL Server Web Links: tips, tutorials, scripts, and more.
- The Best SQL Web Links
- Have a SQL tip to offer your fellow DBA's 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 guru is waiting to answer your technical questions.