Multiple tables

A common use case for SQL statements and database interactions requires the ability to fetch data from multiple tables in a single call. Let's take a look at how that's possible using the query builder.

Basic multi-table query

Retrieving data from more than one table is the same as it would be for a single table. The input property of the selectFrom function chain accepts an array, where each item in the array is a reference to a single table. You can add as many as you need to with this method.

const { data, error } = db
    .selectFrom([
        { table: 'table_1', columns: ['id'] },
        { table: 'table_2', columns: ['column_a'] }
    ])
    .leftJoin('table_1', equalsColumn('table_2.column_a', 'table_1.id'))
    .query()

Last updated