---
title: "Click counter functions: INCR and DECR"
description: "Count views and clicks in CoraDB with INCR and DECR, which read a row and change a counter column in the same SELECT."
url: "https://www.coradb.ai/manual/sql/function/clickcounter_fn.html"
markdown_url: "https://www.coradb.ai/manual/markdown/sql/function/clickcounter_fn.md"
product: "CoraDB"
version: "1.0"
keywords: "incr, decr, click counter, view counter, with increment for, coradb"
---

# Click counter functions: INCR and DECR

```text
INCR(column_name)
DECR(column_name)

SELECT ... FROM ... WHERE ... WITH {INCREMENT | DECREMENT} FOR column_name
```

`INCR` and `DECR` read a row and, in the same `SELECT`, add 1 to or subtract 1 from an integer column of that row. They are designed for *click counters*, such as the number of times a product page was viewed: one statement both shows the row and records the view, without a separate `UPDATE`.

- The column must be `SMALLINT`, `INTEGER` or `BIGINT`. **Return type:** the type of the column.
- The value returned is the value **before** the change. Write `INCR(col) + 1` to show the new value.
- If the value is `NULL`, it stays `NULL`.
- When the value would pass the maximum (or, for `DECR`, the minimum) of the type, it is reset to 0.
- `WITH INCREMENT FOR column` (or `WITH DECREMENT FOR column`) after the `WHERE` clause changes the counter without listing the function in the select list.

```sql
CREATE TABLE product_view (product_id INT PRIMARY KEY, views INT NOT NULL DEFAULT 0);
INSERT INTO product_view (product_id) VALUES (1795), (123), (335);

-- show the product and count the view
SELECT p.name, INCR(v.views)
FROM product_view v JOIN product p ON p.id = v.product_id
WHERE v.product_id = 1795;
```

| name | views |
|---|---:|
| Balboa Persistence Tee | 0 |

The stored value is now 1. The same with `WITH INCREMENT FOR` returns 1 and stores 2:

```sql
SELECT product_id, views FROM product_view
WHERE product_id = 1795
WITH INCREMENT FOR views;
```

> **Warning:**
> - The change is made immediately and independently of the transaction: a `ROLLBACK` does not undo it.
> - The `SELECT` must return exactly one row; otherwise it fails with `Query result contains more than a single tuple`.
> - The functions work only in a top-level `SELECT`, not in a subquery or in `INSERT ... SELECT` or `UPDATE ... SET col = (SELECT ...)`.
> - If several `INCR`/`DECR` calls are in one statement and one fails, none of them is applied.
> - The change bypasses `UPDATE` triggers. A trigger that rejects updates on the table, for example, does not stop `INCR`.
