Skip to Content
MySQL Cookbook, 2nd Edition
book

MySQL Cookbook, 2nd Edition

by Paul DuBois
November 2006
Intermediate to advanced
977 pages
30h 42m
English
O'Reilly Media, Inc.
Content preview from MySQL Cookbook, 2nd Edition

Calculating LIMIT Values from Expressions

Problem

You want to use expressions to specify the arguments for LIMIT.

Solution

Sadly, you cannot. You can use only literal integers—unless you issue the statement from within a program, in which case you can evaluate the expressions yourself and insert the resulting values into the statement string.

Discussion

Arguments to LIMIT must be literal integers, not expressions. Statements such as the following are illegal:

SELECT * FROM profile LIMIT 5+5;
SELECT * FROM profile LIMIT @skip_count, @show_count;

The same no expressions allowed principle applies if you’re using an expression to calculate a LIMIT value in a program that constructs a statement string. You must evaluate the expression first, and then place the resulting value in the statement. For example, if you produce a statement string in Perl or PHP as follows, an error will result when you attempt to execute the statement:

$str = "SELECT * FROM profile LIMIT $x + $y";

To avoid the problem, evaluate the expression first:

$z = $x + $y;
$str = "SELECT * FROM profile LIMIT $z";

Or do this (but don’t omit the parentheses or the expression won’t evaluate properly):

$str = "SELECT * FROM profile LIMIT " . ($x + $y);

If you’re constructing a two-argument LIMIT clause, evaluate both expressions before placing them into the statement string.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

MySQL Cookbook, 3rd Edition

MySQL Cookbook, 3rd Edition

Paul DuBois
MySQL 8 Cookbook

MySQL 8 Cookbook

Karthik Appigatla
MySQL Cookbook

MySQL Cookbook

Paul DuBois
MySQL Cookbook, 4th Edition

MySQL Cookbook, 4th Edition

Sveta Smirnova, Alkin Tezuysal

Publisher Resources

ISBN: 059652708XSupplemental ContentErrata Page