Is it possible to set up a column in MySQL to automatically update an INT(11) column with the current Unix timestamp value on an UPDATE? I tried everything and can't seem to get it working. I can make it work as a default value on an insert using unix_timestamp().
No.
Only the timestamp and datetime datatypes support the on update clause.
In recent versions of MySQL though, you can combine an auto-updated timestamp column with a computed column that turns it to a unix timestamp - which avoids the need for a trigger:
create table mytable (
id int primary key,
-- auto-updated timestamp colum
update_ts timestamp on update current_timestamp,
-- unix timestamp computed from the timestamp
unix_update_ts int as (timestampdiff(second, '1970-01-01', update_ts))
);
Note that we cannot use unix_timestamp() in a computed column as of now; MySQL seems to assume that the results of this function are not deterministic (which is not correct when the function is given a fixed argument) - but we can work around this with timestampdiff().
You can do this with a DATETIME or TIMESTAMP column:
CREATE TABLE mytable (
id SERIAL PRIMARY KEY,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP() ON UPDATE CURRENT_TIMESTAMP()
);
Then you can query it to get the UNIX timestamp like this:
SELECT UNIX_TIMESTAMP(timestamp) AS ts FROM mytable;
MySQL 5.7 has generated columns, but it doesn't work with nondeterministic functions:
mysql> ALTER TABLE mytable ADD COLUMN ts INT UNSIGNED AS (UNIX_TIMESTAMP(timestamp));
ERROR 3102 (HY000): Expression of generated column 'ts' contains a disallowed function.
You could define a trigger:
mysql> ALTER TABLE mytable ADD COLUMN ts INT UNSIGNED;
mysql> CREATE TRIGGER ts BEFORE UPDATE ON mytable FOR EACH ROW SET NEW.ts = UNIX_TIMESTAMP(NEW.timestamp);
mysql> select * from mytable;
+----+---------------------+------+
| id | timestamp | ts |
+----+---------------------+------+
| 2 | 2020-07-23 23:09:57 | NULL |
+----+---------------------+------+
mysql> update mytable set id = 3;
mysql> select * from mytable;
+----+---------------------+------------+
| id | timestamp | ts |
+----+---------------------+------------+
| 3 | 2020-07-23 23:14:05 | 1595546045 |
+----+---------------------+------------+
You should create a matching trigger before insert as well.