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
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!