5

I am trying this code to use LIMIT in MYSQL with a variable. When I use a simple number for LIMIT it works fine but when I use a variable then it's not working.

SET @increment:=9;
SET @number:=1;
SET @end:=10*@number;
SET @start:=@end-@increment;

SELECT name, detail FROM tab1 LIMIT @start, @end;

When I use the below code (no variable) it works fine:

SELECT name, detail FROM tab1 LIMIT 0,10;

enter image description here

2 Answers 2

4

I'm using in this way. Maybe it'll help you.

SET @increment := 4;
SET @number := 1;
SET @end := 5 * @number;
SET @start := @end - @increment;


PREPARE stmt FROM 'SELECT @i := total, user FROM logintable LIMIT ?,?';
EXECUTE stmt USING @start, @end;

SELECT @i AS result;
Sign up to request clarification or add additional context in comments.

2 Comments

This should be the accepted answer as it is the only way to achieve it.
@Constantin Actually there is another way too: instead of using user-defined variables, you can declare local variables using DECLARE statement. Variables declared in such way can be used with the LIMIT clause.
0

The values need to be constant.

According to the spec:

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.

https://dev.mysql.com/doc/refman/5.5/en/select.html

1 Comment

then how to get the specific record from database through variable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.