Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

SlimPickins's avatar

Simple math in DB query

I am trying to query my DB and return results where the 'speed' column is 10+km/h over the 'speed_limit' column.

I am using a query builder to take variables out of the request and build them similar to this:

if($overSpeed != false){ $query = $query->where('speed', '>', 'speed_limit' + 10); }

I've tried variations of the following: $query = $query->where('speed', '>', 'speed_limit' + 10); $query = $query->where('speed', '>', '(speed_limit + 10)');

And I cannot seemt o get it right. Any help would be appreciated.

0 likes
4 replies
Dunsti's avatar

try to put the field-name in Backticks:

$query->where('speed', '>', `speed_limit` +  10);
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Try a raw query

$query->whereRaw('speed > speed_limit + ?', [10])
//or
$query->whereRaw('speed > speed_limit + 10')
1 like
SlimPickins's avatar

Great answers, thanks to all. This one really had me stuck. Thanks.

Please or to participate in this conversation.