CQN and query performance — SAP Guided Tutorial
Free sample lesson · open to everyone
Writing efficient CAP queries with CQL/CQN: path expressions and nested projections instead of loops, server-side paging limits, and how to see the SQL CAP actually sends so you can fix N+1 problems.
In this lessonShow sectionsHide sections
Visual overview
The situation: a real project scenario
An order list took 14 seconds in production. With DEBUG=sql the team saw 501 statements for 500 rows: an after READ handler loaded each customer separately. Replacing the loop with a nested projection reduced it to one statement and the page loaded in under a second.
Explanation
CAP gives you a query language called CQL — statements like SELECT.from(Books).where(...) — which compiles down to CQN, a JSON representation of the query, before the database service translates that into actual SQL.
The common building blocks are straightforward: await SELECT.from(Books).where({ stock: { '<': 10 } }).columns('ID', 'title') for reads, SELECT.one.from(Books, id) to read a single row by key, UPDATE(Books, id).set({ stock: 0 }), and INSERT.into(Orders).entries(data). Tagged-template syntax such as .where\stock < ${n}\`` is parameterized automatically, which is what keeps these queries safe from SQL injection without you having to think about escaping.
The most common performance bug in CAP code by far is N+1: issuing one query per row inside a loop, for example reading each order's customer separately with await SELECT.one.from(Customers, o.customer_ID) inside a for loop.
The fix is to fetch related data in the same query using a path expression or a nested projection, such as SELECT.from(Orders).columns(o => { o.ID, o.customer(c => c.name) }), which produces one statement with a join instead of one statement per row.
Where a nested projection doesn't fit, collecting the relevant keys up front and reading them all at once with where({ ID: { in: ids } }) achieves the same effect.
The failure mode to watch for beyond N+1 is pulling whole tables into JavaScript and filtering there — it passes quietly in tests with a handful of rows and then falls over in production.
Paging is the other lever that matters at scale. cds.query.limit.default and .max (or @cds.query.limit on a specific entity) cap how many rows a single request can return, which protects you from a request that accidentally tries to return millions of rows. Fiori elements pages automatically against these limits, but custom clients need to page explicitly with $top/$skip or $skiptoken; $count=true is also worth using sparingly on large tables, since counting the full result set can be expensive even when the actual page returned is small.
To see what your handlers are really doing, start cds watch with DEBUG=sql (or set the SQL logger's level) and watch every statement get printed. A page that issues dozens of near-identical SELECTs for what should be one request is the signature of N+1. On HANA specifically, the SQL plan cache and explain plan are the tools for diagnosing a slow statement and checking that its filters are actually hitting indexed columns rather than forcing a full scan.
To practice this directly: write an after READ handler that loads each order's customer in a loop and count the SQL statements with DEBUG=sql; rewrite it using a nested projection and count again; set a maximum page size of 1000 and request $top=5000 to see the limit actually applied; then add $count=true and compare response time on a large generated dataset. The target to hit is that your heaviest list request issues a constant number of SQL statements no matter how many rows come back.
Code example
// N+1 (bad)for (const o of orders) o.customerName = (await SELECT.one.from(Customers, o.customer_ID)).name; // One statement (good)const orders = await SELECT.from(Orders).columns(o => { o.ID, o.createdAt, o.customer(c => { c.name })}).where({ status: 'OPEN' }).limit(100);Watch out
Common mistakes
- Running one query per row in loops or after handlers.
- Reading full tables and filtering in JavaScript.
- Concatenating user input into query strings instead of parameterised templates.
- Removing the page size limit because one report needed all rows.
Do this
Best practices
- Use path expressions and nested projections to fetch related data in one statement.
- Keep server-side paging limits and design reports to page or aggregate on the database.
- Check SQL statement counts per request in tests with realistic data volumes.
In the interview
Interview angle
Performance questions are about evidence. Explain CQL vs CQN, show the N+1 pattern and its fix, mention paging limits, and describe how you measured it — statement counts with DEBUG=sql and plan analysis on HANA.
Practice this lesson
Original educational case studies for SAP consultants, not official SAP certification exam questions. Verify product edition and implementation details against the current SAP documentation.
Quick check
0 of 4 questions attempted
Question 1 of 4
A list request runs 501 SQL statements for 500 rows. What is the most likely cause?
Question 2 of 4
What is CQN in CAP?
Question 3 of 4
Which CAP feature protects the server from requests that try to return millions of rows?
Question 4 of 4
Why is `.where`title = ${input}`` safe from SQL injection in CAP?
Practise this in an interview
Answer in your own words and get instant feedback, the way an interviewer would judge it.
1A Fiori list report on a CAP service is slow in production but fast in development. How do you investigate?
2How do nested projections in CQL help performance?
Was this lesson helpful?
Keep exploring
Check before use: lesson examples are educational, not a guarantee of correctness for your SAP edition or release. Sample code has not been executed on your SAP system. Confirm API availability, syntax, authorizations and business impact in an approved development or test environment.