© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
Drizzle TeamDT
Drizzle Team•16mo ago•
1 reply
Mike J

How would you write this SQL query using Drizzle?

Hey! This is my first time using Drizzle. I have the following SQL query, which returns the ID for "my_name" (which I expect to return most of the time). If the name doesn't exist, it will insert it into the table and return the new ID. It's one call to the database and avoids trying to INSERT only if the value doesn't exist.

How do I write this using Drizzle?

WITH ins AS (
    INSERT INTO names (name)
    VALUES ('my_name')
    ON CONFLICT (name) DO NOTHING
    RETURNING id
)
SELECT COALESCE(
    (SELECT id FROM your_table WHERE name = 'your_name'),
    (SELECT id FROM ins)
);
WITH ins AS (
    INSERT INTO names (name)
    VALUES ('my_name')
    ON CONFLICT (name) DO NOTHING
    RETURNING id
)
SELECT COALESCE(
    (SELECT id FROM your_table WHERE name = 'your_name'),
    (SELECT id FROM ins)
);
Drizzle TeamJoin
The official Discord for all Drizzle related projects, such as Drizzle ORM, Drizzle Kit, Drizzle Studio and more!
11,879Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

How would you write this REPLACE query?
Drizzle TeamDTDrizzle Team / help
3y ago
Write SQL query in Drizzle?
Drizzle TeamDTDrizzle Team / help
2y ago
Drizzle as SQL query generator
Drizzle TeamDTDrizzle Team / help
3y ago
Natively write SQL functions/triggers with Drizzle?
Drizzle TeamDTDrizzle Team / help
16mo ago