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

rotaercz's avatar

How can I do an orderBy query for data that is stored in JSON format?

So for example when the data is in string format I can do something like this:

->orderBy(DB::raw('FIELD(animal_type, "fish", "amphibian", "reptile", "bird", "mammal", "") ASC, animal_type'))

But if the data for 'animal_type' is stored in JSON format like this:

["vertebrate", "amphibian"]

Let's say I have a table that looks like this:

|id|animal|animal_type|
|--| --- | --- |
|1 |Leaf green tree frog |["vertebrate", "amphibian", "ectothermic", "pelodryadidae"]|
|2 |Seymouria|["vertebrate", "amphibian"]|
|3 |Dermophis mexicanus|["amphibian"]|
|4 |Old World sparrow|["vertebrate", "bird"]|
|5 |Parrot|["vertebrate", "bird", "psittacines"]|
|6 |African bush elephant|["vertebrate", "mammal"]|

Ideally I'd like to sort by a single characteristic of the animal. Say order by "bird", "amphibian". Then the result would look like:

Old World sparrow
Parrot
Leaf green tree frog
Seymouria
Dermophis mexicanus

How would I go about creating a query that can do an orderBy in this kind of scenario?

EDIT: MySQL 8.0 introduces a JSON function that can help: https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#operator_member-of

A pure MySQL query would look something like this:

select * from mytable order by 
    'bird' member of(animal_type) desc, 
    'amphibian' member of(animal_type) desc;

How can I do this in the Laravel way?

0 likes
7 replies
jlrdw's avatar

I suggest putting the data in a table, makes things so mush easier.

rotaercz's avatar

@jlrdw It's kind of difficult due to the animal_type being of a variable length. I've updated the question to help clarify the problem.

SilenceBringer's avatar

@rotaercz like this (didn't really check, may conatins some errors)

->orderByRaw('if(json_contains(`jtest`, \'"bird"\'), 1, 0) desc')
->orderByRaw('if(json_contains(`jtest`, \'"amphibian"\'), 1, 0) desc')

By the way, I think it's bad idea to order by data stored in json column. You need to restructure your database

rotaercz's avatar

@SilenceBringer I think in this scenario it makes sense for the data to be in json format. You'll notice the number of attributes varies by animal. If I made a column per attribute there would be a lot of wasted space.

SilenceBringer's avatar

@rotaercz in case you need to filter/order by data in json column - for sure it make sence to restructure db and not store it in json column.

Or think about using non-relational database

jlrdw's avatar

@rotaercz setup correct relational data. Even if you use nested sets, still better than json.

Please or to participate in this conversation.