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
XafetsOP16mo ago
Bump
ccabd
ccabd16mo 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
XafetsOP16mo ago
Then you're selecting the entire object though
ccabd
ccabd16mo ago
i fail to see the issue here
Xafets
XafetsOP16mo ago
Selecting only the columns you need vs all columns improves performance, CPU usage, and billing
Angelelz
Angelelz16mo 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
Piotrek16mo ago
Doesn't the insert method return an object with insertId already tho?
Angelelz
Angelelz16mo ago
I'm assuming your using pg.
Xafets
XafetsOP16mo ago
Doesn't returning(...) affect the DB read? Yeah, pg
Angelelz
Angelelz16mo 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
XafetsOP16mo ago
Exactly. Sounds like this is the shortest syntax, which works, but is too verbose IMO
Angelelz
Angelelz16mo 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
Angelelz16mo 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
Piotrek16mo ago
Oh ok, good to know haha
Xafets
XafetsOP16mo ago
According to the docs, you do not get this for MySQL https://orm.drizzle.team/docs/crud#insert-returning
Piotrek
Piotrek16mo ago
Yeah, returning is not for MySQL, however insertId is for MySQL exclusively weird ¯\_(ツ)_/¯
Angelelz
Angelelz16mo ago
There you go then!
Want results from more Discord servers?
Add your server