Get `id` of inserted row

Is this the right way to get the id of an insert? It feels incredibly cumbersome for such a common pattern, so feel like I'm doing something wrong:
const { resultId } = (await Database.insert(UsersTable).values(userInsert).returning({resultId: UsersTable.id}))[0]
const { resultId } = (await Database.insert(UsersTable).values(userInsert).returning({resultId: UsersTable.id}))[0]
17 Replies
Xafets
Xafets12mo ago
Bump
ccabd
ccabd12mo ago
well you can skip creating a return type
const resultId = (await Database.insert(UsersTable).values(userInsert).returning())[0].id
const resultId = (await Database.insert(UsersTable).values(userInsert).returning())[0].id
Xafets
Xafets12mo ago
Then you're selecting the entire object though
ccabd
ccabd12mo ago
i fail to see the issue here
Xafets
Xafets11mo ago
Selecting only the columns you need vs all columns improves performance, CPU usage, and billing
Angelelz
Angelelz11mo ago
The way you handle the response from your driver doesn't have anything to do with DB reads. What is your driver BTW?
Piotrek
Piotrek11mo ago
Doesn't the insert method return an object with insertId already tho?
Angelelz
Angelelz11mo ago
I'm assuming your using pg.
Xafets
Xafets11mo ago
Doesn't returning(...) affect the DB read? Yeah, pg
Angelelz
Angelelz11mo ago
Oh, I get it now. the returning method lets you select what you want, but i'm not sure if that is implemented in the DB level
Xafets
Xafets11mo ago
Exactly. Sounds like this is the shortest syntax, which works, but is too verbose IMO
Angelelz
Angelelz11mo ago
GitHub
drizzle-orm/drizzle-orm/src/pg-core/dialect.ts at main · drizzle-te...
TypeScript ORM that feels like writing SQL. Contribute to drizzle-team/drizzle-orm development by creating an account on GitHub.
Angelelz
Angelelz11mo ago
So yeah! that is the syntax you should use Now, I'm not super familiar with pg. But, don't you get the insertedId from the insert method without the returning? That is the case for mysql but I don't know in pg.
Piotrek
Piotrek11mo ago
Oh ok, good to know haha
Xafets
Xafets11mo ago
According to the docs, you do not get this for MySQL https://orm.drizzle.team/docs/crud#insert-returning
Piotrek
Piotrek11mo ago
Yeah, returning is not for MySQL, however insertId is for MySQL exclusively weird ¯\_(ツ)_/¯
Angelelz
Angelelz11mo ago
There you go then!
Want results from more Discord servers?
Add your server
More Posts