import { kysely } from "https://dotland.deno.dev/x/kysely_postgrs_js_dialect@v0.27.4/deps.ts";
const { QueryCreator } = kysely;
Creates a select
query builder for the given table or tables.
The tables passed to this method are built as the query's from
clause.
Examples
Create a select query for one table:
db.selectFrom('person').selectAll()
The generated SQL (PostgreSQL):
select * from "person"
Create a select query for one table with an alias:
const persons = await db.selectFrom('person as p')
.select(['p.id', 'first_name'])
.execute()
console.log(persons[0].id)
The generated SQL (PostgreSQL):
select "p"."id", "first_name" from "person" as "p"
Create a select query from a subquery:
const persons = await db.selectFrom(
(eb) => eb.selectFrom('person').select('person.id as identifier').as('p')
)
.select('p.identifier')
.execute()
console.log(persons[0].identifier)
The generated SQL (PostgreSQL):
select "p"."identifier",
from (
select "person"."id" as "identifier" from "person"
) as p
Create a select query from raw sql:
import { sql } from 'kysely'
const items = await db
.selectFrom(sql<{ one: number }>`(select 1 as one)`.as('q'))
.select('q.one')
.execute()
console.log(items[0].one)
The generated SQL (PostgreSQL):
select "q"."one",
from (
select 1 as one
) as q
When you use the sql
tag you need to also provide the result type of the
raw snippet / query so that Kysely can figure out what columns are
available for the rest of the query.
The selectFrom
method also accepts an array for multiple tables. All
the above examples can also be used in an array.
import { sql } from 'kysely'
const items = await db.selectFrom([
'person as p',
db.selectFrom('pet').select('pet.species').as('a'),
sql<{ one: number }>`(select 1 as one)`.as('q')
])
.select(['p.id', 'a.species', 'q.one'])
.execute()
The generated SQL (PostgreSQL):
select "p".id, "a"."species", "q"."one"
from
"person" as "p",
(select "pet"."species" from "pet") as a,
(select 1 as one) as "q"