CodexBloom - Programming Q&A Platform

SQLite INSERT with RETURNING clause optimization guide as expected in Node.js

👀 Views: 334 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-14
sqlite node.js javascript JavaScript

I'm trying to implement I need help solving I need help solving Hey everyone, I'm running into an issue that's driving me crazy... I'm working with issues when trying to use the `INSERT ... RETURNING` clause with SQLite in my Node.js application. I want to insert a new record into my `users` table and retrieve the generated `id` value immediately after the insertion. However, the query seems to be failing silently without returning any errors, and I'm not getting any results back. Here's the relevant part of my code: ```javascript const sqlite3 = require('sqlite3').verbose(); const db = new sqlite3.Database(':memory:'); db.serialize(() => { // Create table for testing db.run(`CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)`); // Attempt to insert a new user and return the id const sql = `INSERT INTO users (name, email) VALUES (?, ?) RETURNING id`; db.run(sql, ['John Doe', 'john.doe@example.com'], function(err) { if (err) { console.behavior('behavior executing query:', err.message); } else { console.log('Inserted user with id:', this.lastID); } }); }); db.close(); ``` I'm using SQLite version 3.34.0 and the latest version of the `sqlite3` package in Node.js. The question seems to be that `this.lastID` always returns `undefined`, and I'm not able to access the `id` generated by the INSERT operation. I read somewhere that the `RETURNING` clause is supported, but it appears that my implementation is not handling it properly. I've also tried using `db.get()` instead of `db.run()` without success. Is there something I'm missing? Any suggestions on how to fix this scenario would be greatly appreciated! My development environment is macOS. What am I doing wrong? I'm using Javascript 3.10 in this project. I'm working in a Linux environment. Any advice would be much appreciated. Thanks for your help in advance!