Click counter functions: INCR and DECR
INCR(column_name)DECR(column_name)
SELECT ... FROM ... WHERE ... WITH {INCREMENT | DECREMENT} FOR column_nameINCR 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,INTEGERorBIGINT. Return type: the type of the column. - The value returned is the value before the change. Write
INCR(col) + 1to show the new value. - If the value is
NULL, it staysNULL. - When the value would pass the maximum (or, for
DECR, the minimum) of the type, it is reset to 0. WITH INCREMENT FOR column(orWITH DECREMENT FOR column) after theWHEREclause 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 viewSELECT p.name, INCR(v.views)FROM product_view v JOIN product p ON p.id = v.product_idWHERE 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_viewWHERE product_id = 1795WITH INCREMENT FOR views;