I have a database table with two columns updated_at
and children_updated_at
and I would like to show the latest modified records first based on the SQL function GREATEST(updated_at, children_updated_at)
.
The SQL query I’d like to generate is:
select * from Account ORDER BY GREATEST(updated_at, children_updated_at);
The output should be ordered with the highest value of either updated_at
or children_updated_at
first.
An input table like this:
name | updated_at | children_updated_at |
---|---|---|
User 1 | 2024-05-07 10:00:00.000 | 2024-05-07 13:00:00.000 |
User 2 | 2024-05-07 11:00:00.000 | 2024-05-07 09:00:00.000 |
User 3 | 2024-05-07 12:00:00.000 | 2024-05-07 10:00:00.000 |
Should generate an output like this:
[
{ "name": "User 1",
"updated_at": "2024-05-07 10:00:00.000",
"children_updated_at": "2024-05-07 13:00:00.000"
},
{ "name": "User 3",
"updated_at": "2024-05-07 12:00:00.000",
"children_updated_at": "2024-05-07 10:00:00.000"
},
{ "name": "User 2",
"updated_at": "2024-05-07 11:00:00.000",
"children_updated_at": "2024-05-07 09:00:00.000"
}
]
I could not find anything about using GREATEST()
or other SQL functions that combine columns in the Prisma documentation.
The actual query is a lot more complex, and because of that a raw sql query will not work for me.
Is there a way to achieve this requirement using Prisma ORM?
2
Answers
First create a indicator column and do order by on that column
MySQL query:
or
or
View Result: db<>fiddle
Output:
GREATEST(dt1, dt2)
Will work. But if any date is null, then it will not work.So, better use
GREATEST(COALESCE(dt1, 0), COALESCE(dt2, 0))
Prisma does not directly support using functions like GREATEST. However, you can achieve similar functionality by using a combination of Prisma’s .orderBy() method wit js
This example will fetch the records from the database ordered first by updatedAt in descending order, and then by childrenUpdatedAt in descending order.
Hope this works for you…