In Memory Tables · Selecting Data · Practice Question
Return Last N Rows of Table
Question
Given the following table:
t:([] sym:`AAPL`MSFT`GOOG`TSLA`NVDA;
qty:100 200 150 75 300;
price:185.25 410.10 142.80 238.50 875.20)Result:
sym qty price
-----------------
AAPL 100 185.25
MSFT 200 410.1
GOOG 150 142.8
TSLA 75 238.5
NVDA 300 875.2Return the last 3 rows of the table.
Solution
Method 1
-3#tMethod 2
-3 sublist tMethod 3
select [-3] from tResult:
sym qty price
--------------
GOOG 150 142.8
TSLA 75 238.5
NVDA 300 875.2Explanation
Using Take
The Take operator can be used with a negative number to return rows from the end of a table:
-3#tResult:
sym qty price
--------------
GOOG 150 142.8
TSLA 75 238.5
NVDA 300 875.2Using Sublist
The same result can be obtained using:
-3 sublist tResult:
sym qty price
--------------
GOOG 150 142.8
TSLA 75 238.5
NVDA 300 875.2The sublist function returns a contiguous subset of rows from a table or list.
Using qSQL
qSQL provides built-in support for limiting the number of rows returned:
select [-3] from tResult:
sym qty price
--------------
GOOG 150 142.8
TSLA 75 238.5
NVDA 300 875.2This approach is often convenient when the rows are already being filtered or transformed using qSQL.
For example:
select [-3] from t where qty>100can be combined naturally with other qSQL operations.
Why Use Sublist Instead of Take?
For tables with sufficient rows, both approaches produce the same result:
-3#tand
-3 sublist tHowever, they behave differently when more rows are requested than are available.
Consider a table containing only two rows:
small:2#tResult:
sym qty price
---------------
AAPL 100 185.25
MSFT 200 410.1Using Take:
-5#smallResult:
sym qty price
---------------
MSFT 200 410.1
AAPL 100 185.25
MSFT 200 410.1
AAPL 100 185.25
MSFT 200 410.1Notice that rows are repeated in order to satisfy the request for five rows.
Using Sublist:
-5 sublist smallResult:
sym qty price
---------------
AAPL 100 185.25
MSFT 200 410.1No rows are duplicated.
Summary
| Method | Behaviour |
|---|---|
-3#t | Returns the last 3 rows, repeating rows if necessary |
-3 sublist t | Returns up to the last 3 rows, never duplicates rows |
select [-3] from t | qSQL equivalent, useful when already working with qSQL |
When selecting a subset of rows from a table, sublist is often the safer choice because it never manufactures additional rows when the requested count exceeds the size of the table.