Kysely: Select queries

With the db Kysely object imported in a file, we can now run queries.

Let’s start with SELECT.

We can select all items from a table, returning all fields, using:

const items = await db
  .selectFrom('tablename')
  .selectAll()
  .execute()

You might just want to get a specific field, and you can use .select() instead of .selectAll():

const items = await db
  .selectFrom('tablename')
  .select('name')
  .execute()

You can add a WHERE to filter rows that satisfy a specific requirement:

const items = await db
  .selectFrom('tablename')
  .selectAll()
  .where('name', '=', 'test')
  .execute()

Here are some other simple examples of using .where():

.where('age', '>', 18)

# 

.where('id', 'in', [1, 2, 3])

You can do fancy stuff here, like doing OR / AND logic, or conditionals.

Running .execute() at the end runs the query and returns the result in an array.

Maybe we only want to get one item from the table, for example if a field is UNIQUE. In this case you might want to use executeTakeFirst():

const item = await db
  .selectFrom('tablename')
  .selectAll()
  .where('email', '=', '[email protected]')
  .executeTakeFirst()

Lessons in this unit:

0: Introduction
1: Installing Kysely
2: ▶︎ Select queries
3: Inserting data
4: Deleting data
5: Updating data
6: Joins
Want to learn more? Check out our courses