drift icon indicating copy to clipboard operation
drift copied to clipboard

use CASE WHEN IN MOOR

Open Ahmed-elshorbagy opened this issue 5 years ago • 1 comments

How to effeciently implement multiple case when in moor to mimic this sql

SELECT trackid,name
CASE
             WHEN milliseconds<60000    THEN
                 'short'
              When milliseconds>60000 And milliseconds<300000 THEN 'medium'
              ELSE   'long'
              END category
FROM tracks;

Thanks in advance

Ahmed-elshorbagy avatar Sep 04 '20 18:09 Ahmed-elshorbagy

We don't (yet) support CASE from the Dart query builder. Of course, you can use CASE expressions in custom queries or moor files.

In your case, you're only using the CASE expression in a result column, so you might as well implement this in Dart:

final result = select(tracks).map((track) {
  String category;
  if (track < 60000) {
    category = 'short';
  } else if (track < 300000) {
    category = 'medium';
  } else {
    category = 'long';
  }
  
  // ...
}).getAll();

simolus3 avatar Sep 04 '20 19:09 simolus3

Must have missed this issue - caseMatch has been available for some time.

simolus3 avatar Nov 24 '22 08:11 simolus3