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

iPurpl3x's avatar

Query doesn't get executed when using orderByRaw()

I'm rather new to Laravel (ex frontend dev here) and today I've run into my first issue that I cannot figure out.

So I'm running a query on my User model and I am trying to use a raw statement for ordering :

$query = User::query()
    ->whereNotIn('username', $blockedUsers)
    ->orderByRaw('FLOOR(((comment_count - discussion_count) * 10 + discussion_count * 21 + votes * 31) / 135) DESC')
    ->offset($offset)
    ->take($limit)
    ->get();

The query runs perfectly fine when I try it on my dev environment but it doesn't get executed (and I get an empty list as result) when I try it on my production environment. I have checked the MYSQL logs and I was surprised to see that the query is Prepared and then Executed on my dev environment and only Prepared on my production environment.

When I change the query to this in my code, everything works fine, also on production :

$query = User::query()
    ->whereNotIn('username', $blockedUsers)
    ->orderBy('votes', 'desc')
    ->offset($offset)
    ->take($limit)
    ->get();

But now the results are not really in the right order...

This is a real mystery to me, if anyone has a clue, please let me know.

0 likes
3 replies
nkarlis's avatar

@ipurpl3x I believe i managed to replicate your issue. I didn't get results too by using orderByRaw() method.

I started playing with it by deleting parts of it. I found that the subtraction part (comment_count - discussion_count) was the issue.

I tried to run the query produced by the above code (using toSql () instead of get()) directly in mysql cli and i got the error "BIGINT UNSIGNED value is out of range...".

So i believe your problem is that if your database columns are registered as unsigned then an arithmetic underflow error is produced by mysql during that subtraction that is never returned.

1 like
staudenmeir's avatar
Level 24

You need to cast both columns as signed integers:

->orderByRaw('FLOOR(((cast(comment_count as signed) - cast(discussion_count as signed)) * 10 + discussion_count * 21 + votes * 31) / 135) DESC')
2 likes
iPurpl3x's avatar

Alright that worked. Thank you very much for your precious help!

Please or to participate in this conversation.