Does Ruby Sequel have an equivalent for the SQL "coalesce" function?
Asked Answered
W

2

6

In SQL in order to avoid getting a NULL value, I can use the "coalesce" function to substitute it like so:

SELECT COALESCE(some_column, 0) FROM some_table;  

But I can't find any way to do the same thing using Sequel.

Welladvised answered 5/8, 2013 at 13:59 Comment(0)
C
9

DB[:some_table].select{coalesce(some_column, 0)}

Consonantal answered 5/8, 2013 at 18:59 Comment(0)
N
2

An alternative syntax version is Sequel.function(:coalesce,:some_column,5).

Example:

require 'sequel'
Sequel.extension :pretty_table    
DB = Sequel.sqlite
DB.create_table(:mytables){
  primary_key :id
  field :a, :type => :nvarchar, :size => 10
  field :some_column, :type => :fixnum
}

DB[:mytables].insert(:a => 'a1', :some_column => 10)
DB[:mytables].insert(:a => 'a2')

Sequel::PrettyTable.print(
  DB[:mytables].select(:a, :some_column, Sequel.function(:coalesce,:some_column,5))
)

The result:

+--+--------------------------+-----------+
|a |coalesce(`some_column`, 5)|some_column|
+--+--------------------------+-----------+
|a1|                        10|         10|
|a2|                         5|           |
+--+--------------------------+-----------+
Nonstandard answered 19/8, 2015 at 13:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.