Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select N records from a table in mysql

Tags:

mysql

How can I get only 10 records from a table where there are more than 1000 records. I have a test table with rowid, name, cost.

   select  name, cost from test; 

here I want to select only first 10 rows and dont want to select rowid.

like image 786
Murthy Avatar asked Jan 10 '12 15:01

Murthy


People also ask

How do I select n rows in MySQL?

Here's the syntax to select top N rows in MySQL. In the above statement, we list the columns column1, column2, … that you want to select in your query. Also, you need to specify LIMIT n after the table name, where n is the number of rows you want to select. The above query will select top n records in your table.

How can I get only 10 records in MySQL?

The following is the syntax to get the last 10 records from the table. Here, we have used LIMIT clause. SELECT * FROM ( SELECT * FROM yourTableName ORDER BY id DESC LIMIT 10 )Var1 ORDER BY id ASC; Let us now implement the above query.

How do you select nth record in a table?

ROW_NUMBER (Window Function) ROW_NUMBER (Window Function) is a standard way of selecting the nth row of a table. It is supported by all the major databases like MySQL, SQL Server, Oracle, PostgreSQL, SQLite, etc.

How do I display only 10 records in SQL?

To select first 10 elements from a database using SQL ORDER BY clause with LIMIT 10. Insert some records in the table using insert command. Display all records from the table using select statement. Here is the alternate query to select first 10 elements.


2 Answers

To select the first ten records you can use LIMIT followed by the number of records you need:

SELECT name, cost FROM test LIMIT 10 

To select ten records from a specific location, you can use LIMIT 10, 100

SELECT name, cost FROM test LIMIT 100, 10 

This will display records 101-110

SELECT name, cost FROM test LIMIT 10, 100 

This will display records 11-111

To make sure you retrieve the correct results, make sure you ORDER BY the results too, otherwise the returned rows may be random-ish

You can read more @ http://php.about.com/od/mysqlcommands/g/Limit_sql.htm

like image 126
472084 Avatar answered Oct 11 '22 04:10

472084


You should have an ORDER BY clause when you use LIMIT, so that you will get the same recordset if you call it two times in succession and no data has changed.

So, do something like:

select  name, cost  from test  order by rowid limit 10;  
like image 23
D'Arcy Rittich Avatar answered Oct 11 '22 05:10

D'Arcy Rittich