---
url: https://script-ui.runio.dev/tutorials/big-table.md
---
# 4. A table of 100,000 rows

`table($rows)` gets all its rows from the script, and it searches, sorts and pages them itself. That is quick up to about twenty thousand rows. Beyond that the rows should stay in the database, and the table should ask for one page at a time.

## The tool of the demo

The demo has such a table over 100,000 orders. The tool itself stays short:

```php {12-19}
<?php
// Order archive
// 100,000 orders, read one page at a time.

require_once __DIR__ . '/_archive.php';

use function Runio\ScriptUi\{title, note, table, button, success, warning};

title('Order archive');
note('This table holds one page. Each time it is turned, searched or sorted, it asks for the rows of the page it shows, and for nothing else.');

$picked = table(
    Archive::page(...),      // gets a TableQuery: the search, the order, a limit and an offset
    selectable: true,
    columns: ['id' => 'Order', 'customer' => 'Customer', 'placed' => 'Placed on', 'status' => 'Status', 'total' => 'Total'],
    search: true,
    sortable: ['id', 'customer', 'placed', 'total'],
    count: Archive::count(...),   // gets the search, says how many orders it leaves
);

if (button('Print labels')) {
    if ($picked === []) {
        warning('Tick the orders that need a label first.');
    } else {
        success('Labels are on their way for ' . implode(', ', array_column($picked, 'id')) . '.');
    }
}

```

![The order archive of the demo, searched for "haddad": a table of 25 orders with a search box, headers that sort, and a line that says which rows of how many are shown.](https://script-ui.runio.dev/shots/archive.png){.shot}

In place of the rows, the table gets a function (line 13). It calls that function with a `TableQuery` and gets the rows of one page back. `sortable:` names the columns whose headers can be clicked, and `count:` is a second function that says how many rows the search leaves.

In the demo both functions work the orders out from their numbers, so it needs no database. In a real tool they are two queries.

## With your database

From here on this page is the text of the README, word for word.

A table that gets all its rows is quick up to about twenty thousand of them. For more, pass a function in place of the rows. The table asks it for one page at a time, and the rows stay in the database:

```php
use Runio\ScriptUi\TableQuery;

// To LIKE, % and _ stand for any text. A user who types one means that character.
$like = fn (string $search): string => '%' . strtr($search, ['!' => '!!', '%' => '!%', '_' => '!_']) . '%';

$picked = table(
    function (TableQuery $query) use ($pdo, $like): array {
        $rows = $pdo->prepare(
            "SELECT id, customer, total FROM orders WHERE customer LIKE :search ESCAPE '!'"
            . ' ORDER BY ' . ($query->sort ?? 'id') . ($query->descending ? ' DESC' : ' ASC') . ', id'
            . ' LIMIT :limit OFFSET :offset'
        );
        $rows->bindValue('search', $like($query->search));
        $rows->bindValue('limit', $query->limit, PDO::PARAM_INT);
        $rows->bindValue('offset', $query->offset, PDO::PARAM_INT);
        $rows->execute();

        return $rows->fetchAll(PDO::FETCH_ASSOC);
    },
    selectable: true,
    search: true,
    sortable: ['id', 'customer', 'total'],
    count: function (string $search) use ($pdo, $like): int {
        $count = $pdo->prepare("SELECT COUNT(*) FROM orders WHERE customer LIKE :search ESCAPE '!'");
        $count->execute(['search' => $like($search)]);

        return (int) $count->fetchColumn();
    },
);
```

The function gets a `TableQuery`. Nothing in it is taken from the browser as it came:

| Value | What it holds |
|---|---|
| `search` | What the search box holds, as one line of at most 200 characters, or `''`. Bind it as a parameter, like any text a user typed. |
| `sort` | What the user sorted by: a value out of your `sortable:` list and never anything else, so it may go into the query as it is. `null` while no header was clicked. |
| `descending` | `true` for high to low. |
| `limit`, `offset` | The page, as whole numbers that the table worked out. Without `count:` the limit is one row more than a page holds. |

`sortable:` names the columns whose headers sort. No other header can be clicked. `['customer' => 'c.name']` says what the function gets for a column, which helps in a query with joins. End the order with a column that no two rows share, as the example does with `, id`. Rows that sort alike may otherwise change places between two pages, and one of them shows up twice or not at all.

`count:` gets the search and returns how many rows it leaves. The table then says "Rows 26 to 50 of 100,000" and knows its last page. Leave it out when counting is slow. The table then asks for one row more than a page holds, to see whether another page follows, and offers "Previous" and "Next" without a count.

`search: true` shows the box and hands over what was typed, as one piece of text. What is searched, and how, is up to your query. The table does not split the text into words or look past accents, as it does when it holds all rows. Whether `LIKE` tells upper case from lower case depends on the database: PostgreSQL does and has `ILIKE` for a search that does not. And `LIKE` never matches a column that is `NULL`, not even for an empty search: where `customer` may be `NULL`, search in `COALESCE(customer, '')`.

Ticks count for the page on the screen. The table holds one page, so it returns the ticked rows of that page, as the function returned them in that run. A tick does not travel to another page. When the user turns the page, sorts or searches, the ticked rows that are not on the new page are unticked, and the table says how many they were. It says nothing when the user stayed on their page and a ticked row is gone, as after a button that deleted it. Where the list has more pages than one, the line under the table reads "2 selected on this page". A button still never acts on a row the user does not see.

The table starts again at its first page when it is sorted or searched. When the user changes another input of the tool, it stays on its page while the count is the same, and starts again when the count changed or there is none. A function that returns more rows than it was asked for is turned down with an error: it most likely left out the limit.

The function and `count:` run on every run of the tool: with every click, with every pause while the user types into the search box and with every `refresh()`, also while the table sits in a closed expander or in a tab that is not in view. A page far into the list makes the database pass over all rows before it. So the query has to be one that your database answers quickly: an index on the columns of `sortable:`, a search it can do fast, and no `count:` where counting is slow.

The table shows the columns that the rows of the page have. Name them with `columns:` where not every row has every column, or the headers change from page to page.

Next: [A task that takes long](https://script-ui.runio.dev/tutorials/long-task.md).
