0% found this document useful (0 votes)
14 views2 pages

SECTION 4 Debugging & Performance Optimization

The document outlines a code snippet for an Express.js route that retrieves orders from a database with error handling. It emphasizes the importance of optimizing database queries by avoiding SELECT *, implementing pagination, and ensuring proper indexing and sorting. The section also highlights potential issues with the current implementation that could lead to performance degradation.

Uploaded by

hackmanish963i
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views2 pages

SECTION 4 Debugging & Performance Optimization

The document outlines a code snippet for an Express.js route that retrieves orders from a database with error handling. It emphasizes the importance of optimizing database queries by avoiding SELECT *, implementing pagination, and ensuring proper indexing and sorting. The section also highlights potential issues with the current implementation that could lead to performance degradation.

Uploaded by

hackmanish963i
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SECTION 4: Debugging & Performance Optimization

// Wrap the entire logic in a try-catch block for error handling.

app.get("/orders", async (req, res) => {

try {

// Extract page and limit from the query parameters if not provided then set default values: page
= 1, limit = 10.

const { page = 1, limit = 10 } = req.query;

// Calculate the starting point for fetching data based on the page number and limit.

// number of rows to skip before starting to return data.

const offset = (page - 1) * limit;

// The main query to fetch orders.

// remove SELECT * it is fetching all columns and all rows — this increases the load time.

const orders = await db.query(

`SELECT id, customer_id, order_id

FROM orders

ORDER BY id DESC

LIMIT $1 OFFSET $2`,

[limit, offset] // it will Pass actual values for the placeholders ($1 = limit, $2 = offset).

);

res.send(orders);

} catch (error) {

// If something goes wrong, log the error for debugging.

console.error("Error:", error);

// Return a 503 server is temporarily unavailable.

res.status(503).send("Service Unavailable");

});
These point which is wrong
SELECT * is fetching all columns and all rows — this increases the load time.

No pagination — fetching too much data at once.

No indexing — the database is scanning the entire table instead of using optimized lookup
methods.

No sorting or filtering — the query is unstructured and unoptimized.

You might also like