Search code examples
javascriptnode.jspostgresqlknex.jsbookshelf.js

Knex select from multiple tables


I want to run following SQL with knex:

select * from (
  (select * from foo)
  union all
  (select * from bar)) as biz limit 10 offset 20;

Is there a way to do it without knex.raw?


Solution

  • knex does support union and unionAll. it's documented

    knex.select().from(function() {
        this.select().from('foo')
            .unionAll(function() {
                this.select().from('bar')
            }).as('biz')
    }).limit(10).offset(20).toString()
    

    Output:

    select * from (select * from `foo` union all select * from `bar`) as `biz` limit 10 offset 20