Skip to content

Click counter functions: INCR and DECR

View as Markdown

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

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