SQL integration lets Express apps work with structured data stored in databases. This is essential for saving and retrieving user info, products, or any data your app needs.
app.get('/users', async (req, res) => { const users = await db.query('SELECT * FROM users'); res.json(users.rows); });
When the SQL query succeeds, Express sends the user data as JSON to the client. This is a common way to share data in web apps.
app.get('/products', (req, res) => { const result = db.query('SELECT * FROM products'); res.json(result.rows); });
db.query returns a promise because it runs asynchronously. Without awaiting it or using .then(), the code tries to access rows on a promise object, causing an error.
Option A correctly awaits the async query and sends the rows as JSON. Options A and B miss awaiting the promise. Option A sends the whole data object, not just rows.
app.get('/count', async (req, res) => { const result = await db.query('SELECT COUNT(*) FROM orders'); res.json({ totalOrders: parseInt(result.rows[0].count) }); });
SQL COUNT returns a string number in result.rows[0].count. parseInt converts it to a number. The JSON response sends a number value.