Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query first 10 rows and next time query other 10 rows from table

Tags:

sql

postgresql

I have more than 500 rows with in my Database Table with particular date.

To query the rows with particular date.

select * from msgtable where cdate='18/07/2012' 

This returns 500 rows.

How to query these 500 rows by 10 rows step by step. Query First 10 Rows and show in browser,then query next 10 rows and show in browser?

like image 495
Ramprasad Avatar asked Sep 18 '12 13:09

Ramprasad


People also ask

How do I query last 10 rows in SQL?

mysql> SELECT * FROM ( -> SELECT * FROM Last10RecordsDemo ORDER BY id DESC LIMIT 10 -> )Var1 -> -> ORDER BY id ASC; The following is the output that displays the last 10 records. We can match both records with the help of the SELECT statement.

What is the query to display top 10 rows?

For example, TOP(10) would return the top 10 rows from the full result set. Optional. If PERCENT is specified, then the top rows are based on a percentage of the total result set (as specfied by the top_value). For example, TOP(10) PERCENT would return the top 10% of the full result set.

How will you select 2nd last row from a table?

Here is the query to get the second last row of a table in MySQL. mysql> select *from secondLastDemo order by StudentId DESC LIMIT 1,1; The output displays the second last record.


2 Answers

Just use the LIMIT clause.

SELECT * FROM `msgtable` WHERE `cdate`='18/07/2012' LIMIT 10 

And from the next call you can do this way:

SELECT * FROM `msgtable` WHERE `cdate`='18/07/2012' LIMIT 10 OFFSET 10 

More information on OFFSET and LIMIT on LIMIT and OFFSET.

like image 148
Praveen Kumar Purushothaman Avatar answered Sep 23 '22 02:09

Praveen Kumar Purushothaman


LIMIT limit OFFSET offset will work.

But you need a stable ORDER BY clause, or the values may be ordered differently for the next call (after any write on the table for instance).

SELECT * FROM   msgtable WHERE  cdate = '2012-07-18' ORDER  BY msgtable_id  -- or whatever is stable  LIMIT  10 OFFSET 50;  -- to skip to page 6

Use standard-conforming date style (ISO 8601 in my example), which works irregardless of your locale settings.

Paging will still shift if involved rows are inserted or deleted or changed in relevant columns. It has to.

To avoid that shift or for better performance with big tables use smarter paging strategies:

  • Optimize query with OFFSET on large table
like image 42
Erwin Brandstetter Avatar answered Sep 21 '22 02:09

Erwin Brandstetter