Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make limit offset dynamic using only (My)SQL

Tags:

sql

mysql

limit

This code doesn't work

select pagenr into @offset from pages where id = 3;
select * from table1 limit @offset*10, 10;

What SQLcode do I need to use in order to get this kind of code to work
using only SQL!

Note that

SET SQL_SELECT_LIMIT = @count 

doesn't work because I'm mainly concerned with the offset, not the limit as such.

like image 846
Johan Avatar asked May 03 '11 16:05

Johan


People also ask

Can I use offset without limit in MySQL?

MySQL Offset is used to specify from which row we want the data to retrieve. To be precise, specify which row to start retrieving from. Offset is used along with the LIMIT. Here, LIMIT is nothing but to restrict the number of rows from the output.

How does limit and offset work in MySQL?

In MySQL, the LIMIT clause is used with the SELECT statement to restrict the number of rows in the result set. The Limit Clause accepts one or two arguments that are offset and count. The value of both the parameters can be zero or positive integers.

How do I limit data in MySQL?

Limit Data Selections From a MySQL Database Assume we wish to select all records from 1 - 30 (inclusive) from a table called "Orders". The SQL query would then look like this: $sql = "SELECT * FROM Orders LIMIT 30"; When the SQL query above is run, it will return the first 30 records.

What can I use instead of limit in MySQL?

To get only the specified rows from the table, MySQL uses the LIMIT clause, whereas SQL uses the TOP clause, and Oracle uses the ROWNUM clause with the SELECT statement.


1 Answers

From the MySQL 5.5 specification:

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants, with these exceptions:

  • Within prepared statements, LIMIT parameters can be specified using ? placeholder markers.
  • Within stored programs, LIMIT parameters can be specified using integer-valued routine parameters or local variables as of MySQL 5.5.6.

So, inside a stored procedure, the following would work:

DECLARE offset bigint
SELECT pagenr * 10 INTO offset FROM pages where id = 3;
SELECT * FROM table1 LIMIT offset, 10;

Otherwise, you'll need to precompute the value and pass it in via the query. You should already know the page size and page number, so this shouldn't be difficult.

like image 125
Karelzarath Avatar answered Nov 02 '22 22:11

Karelzarath