Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variable in a LIMIT clause in MySQL

I am writing a stored procedure where I have an input parameter called my_size that is an INTEGER. I want to be able to use it in a LIMIT clause in a SELECT statement. Apparently this is not supported, is there a way to work around this?

# I want something like: SELECT * FROM some_table LIMIT my_size;  # Instead of hardcoding a permanent limit: SELECT * FROM some_table LIMIT 100; 
like image 952
MPX Avatar asked Oct 28 '08 22:10

MPX


People also ask

Can you use variables in MySQL?

Mysql also supports the concept of User-defined variables, which allows passing of a value from one statement to another. A user-defined variable in Mysql is written as @var_name where, var_name is the name of the variable and can consist of alphanumeric characters, ., _, and $.

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.

Can we use limit in MySQL?

MySQL provides a LIMIT clause that is used to specify the number of records to return. The LIMIT clause makes it easy to code multi page results or pagination with SQL, and is very useful on large tables.

How do I limit data 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 which are offset and count. The value of both the parameters can be zero or positive integers.


2 Answers

For those, who cannot use MySQL 5.5.6+ and don't want to write a stored procedure, there is another variant. We can add where clause on a subselect with ROWNUM.

SET @limit = 10; SELECT * FROM (   SELECT instances.*,           @rownum := @rownum + 1 AS rank     FROM instances,           (SELECT @rownum := 0) r ) d WHERE rank < @limit; 
like image 145
ENargit Avatar answered Oct 06 '22 00:10

ENargit


STORED PROCEDURE

DELIMITER $ create PROCEDURE get_users(page_from INT, page_size INT) begin SET @_page_from = page_from; SET @_page_size = page_size; PREPARE stmt FROM "select u.user_id, u.firstname, u.lastname from users u limit ?, ?;"; EXECUTE stmt USING @_page_from, @_page_size; DEALLOCATE PREPARE stmt; end$ DELIMITER ; 

USAGE

call get_users(1, 10); 
like image 21
Pradeep Sanjaya Avatar answered Oct 06 '22 00:10

Pradeep Sanjaya