#SQL Where Like documentation?

1 messages · Page 1 of 1 (latest)

fresh ridge
#

While using Bun's tagged template literal I'm trying to build a query using "WHERE column LIKE key%" with the % suffix I tried look at Bun's Documentation and I couldn't find an example

SELECT *columns* FROM *table* WHERE *column* LIKE ${search_key}%

Solution below

sage berry
# fresh ridge While using Bun's tagged template literal I'm trying to build a query using "WHE...

Hello, just simply normalize your query builder instead of use complex replacement. See example below:

import { SQL } from "bun"
const sql = new SQL("postgresql://...")

// place this to utils.ts
const fulltextPattern = (q) => `%${q}%`

const searchQuery = "blablabla"
const searchPattern = fulltextPattern(searchQuery)
const users = await sql`SELECT * FROM public."users" u WHERE u.first_name ILIKE ${searchPattern} OR u.middle_name ILIKE ${searchPattern}`

// Or just construct the normalize pattern into replacement
const users = await sql`SELECT * FROM public."users" u WHERE u.first_name ILIKE ${"%" + searchQuery + "%"} OR u.middle_name ILIKE ${"%" + searchQuery + "%"}`

This will build sql equivalent with:

SELECT * FROM public."users" u WHERE u.first_name ILIKE '%$1%' OR u.middle_name ILIKE '%$2%'

$1 -> searchPattern
$2 -> searchPattern