Back to Selecting Data

In Memory Tables · Selecting Data · Practice Question

Return Last N Rows of Table

Sign in to track your progress

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.2

Return the last 3 rows of the table.

Solution

Method 1

-3#t

Method 2

-3 sublist t

Method 3

select [-3] from t

Result:

sym  qty price
--------------
GOOG 150 142.8
TSLA 75  238.5
NVDA 300 875.2

Explanation

Using Take

The Take operator can be used with a negative number to return rows from the end of a table:

-3#t

Result:

sym  qty price
--------------
GOOG 150 142.8
TSLA 75  238.5
NVDA 300 875.2

Using Sublist

The same result can be obtained using:

-3 sublist t

Result:

sym  qty price
--------------
GOOG 150 142.8
TSLA 75  238.5
NVDA 300 875.2

The 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 t

Result:

sym  qty price
--------------
GOOG 150 142.8
TSLA 75  238.5
NVDA 300 875.2

This approach is often convenient when the rows are already being filtered or transformed using qSQL.

For example:

select [-3] from t where qty>100

can 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#t

and

-3 sublist t

However, they behave differently when more rows are requested than are available.

Consider a table containing only two rows:

small:2#t

Result:

sym  qty price
---------------
AAPL 100 185.25
MSFT 200 410.1

Using Take:

-5#small

Result:

sym  qty price
---------------
MSFT 200 410.1
AAPL 100 185.25
MSFT 200 410.1
AAPL 100 185.25
MSFT 200 410.1

Notice that rows are repeated in order to satisfy the request for five rows.

Using Sublist:

-5 sublist small

Result:

sym  qty price
---------------
AAPL 100 185.25
MSFT 200 410.1

No rows are duplicated.

Summary

MethodBehaviour
-3#tReturns the last 3 rows, repeating rows if necessary
-3 sublist tReturns up to the last 3 rows, never duplicates rows
select [-3] from tqSQL 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.