rubysequelsequel-gem

Multiple aggregate queries using the sequel gem


Is it possible to use sequel to execute a query like this:

select (select count(*) from users where blah = 'blah') as "users",
       (select count(*) from contacts where blah = 'blah') as "contacts"

I know I can execute these queries one a time using sequel, but I would like to execute them all at the same time.


Solution

  • You can do that query without writing raw SQL with the following:

    dataset = DB.select {[ 
      DB[:users].where(blah: 'blah').select { count('*') }.as(:users),
      DB[:contacts].where(blah: 'blah').select { count('*') }.as(:contacts) 
    ]}
    
    dataset.first
    # => { users: X, contacts: Y }
    
    dataset.sql
    # => "SELECT (SELECT count('*') FROM \"users\" WHERE (\"blah\" = 'blah')) AS \"users\", 
    #            (SELECT count('*') FROM \"contacts\" WHERE (\"blah\" = 'blah')) AS \"contacts\""