Gary Sieling

RethinkDB: CASE WHEN example

There are a couple ways to mimic the SQL “CASE WHEN” in RethinkDB.

If the rows don’t have values in some columns, in SQL you’d default these with “CASE WHEN attr IS NULL … ELSE END”. To fix these, you can use map / merge:

r.db('test').table('users')
  .map(
    (doc) => { return r.expr(
      {
        first_name: '',
        last_name: ''
      }
    ).merge(doc) }
  )

If you want to key off different values, you can use the ‘branch’ function, like so:

r.db('test')
 .table('users')
 .map( 
   (doc) => {
     return {
       first_name: 
         r.branch(
           doc('first_name').eq('test'), 
           1, 
           2)  
     }
   }
  )
Exit mobile version