Update last modified date column - triggers

I have a table like this:
id name modified
11 John 2016-07-12 15:49:45
22 Abraham 2016-07-12 15:52:03
I need to update the 'modified' column which tracks the last modified date for a row. I have done this using a trigger, but have read that triggers eat up performance. Is there a way to do this using constraints?

It's possible to use DEFAULT constraint and DEFAULT keyword in UPDATE clause. See the following example:
CREATE TABLE UpdateTest
(
ID int IDENTITY,
Name varchar(10),
Modified datetime2(2) CONSTRAINT DF_Modified DEFAULT (SYSDATETIME())
)
--ID from IDENTITY, Modified from DEFAULT implicitly
INSERT UpdateTest(Name) VALUES('Test')
--Modified from DEFAULT explicitly
UPDATE UpdateTest SET Name='Test2', Modified=DEFAULT

Related

PostgreSQL serial ID does NOT populate when omitting the value in INSERT statement

I am trying to simply insert JSON data in to a PostgreSQL database. The first column is a serial ID primary key column. When I try to insert the data and omit the serial id value, the serial id value is populated with my first record instead of automatically populating itself.
Example:
CREATE TABLE test (
id SERIAL PRIMARY KEY,
prem_id text,
name text)
Coming from JSON pipeline:
INSERT INTO test VALUES ('1001','Lucy');
INSERT INTO test VALUES ('1002','Johnny');
Table populates as follows:
id | prem_id | name
1001 | Lucy | null
1002 | Johnny | null
If I directly insert from pgAdmin, then I get the same results as above. The only time it works properly is if I add the DEFAULT keyword to the INSERT statement. Just doesn't make sense... All documentation I have read says if you omit this, then it should automatically increment.
I also tried
CREATE TABLE test (
id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
...)
But I am getting a syntax error "at or before GENERATED". I'm really stuck on this one.
Anyone else experience this issue or have any fixes for it?
Much appreciated!
You need to specify the target columns, otherwise the values are matched in the order the columns were defined in the CREATE TABLE statement. You also missed the VALUES clause:
INSERT INTO test
(prem_id, name)
values
('1001','Lucy'),
('1002','Johnny');
Online example

Add column to show a row number in the PostgreSQL [duplicate]

I have a table with existing data. Is there a way to add a primary key without deleting and re-creating the table?
(Updated - Thanks to the people who commented)
Modern Versions of PostgreSQL
Suppose you have a table named test1, to which you want to add an auto-incrementing, primary-key id (surrogate) column. The following command should be sufficient in recent versions of PostgreSQL:
ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;
Older Versions of PostgreSQL
In old versions of PostgreSQL (prior to 8.x?) you had to do all the dirty work. The following sequence of commands should do the trick:
ALTER TABLE test1 ADD COLUMN id INTEGER;
CREATE SEQUENCE test_id_seq OWNED BY test1.id;
ALTER TABLE test1 ALTER COLUMN id SET DEFAULT nextval('test_id_seq');
UPDATE test1 SET id = nextval('test_id_seq');
Again, in recent versions of Postgres this is roughly equivalent to the single command above.
ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;
This is all you need to:
Add the id column
Populate it with a sequence from 1 to count(*).
Set it as primary key / not null.
Credit is given to #resnyanskiy who gave this answer in a comment.
To use an identity column in v10,
ALTER TABLE test
ADD COLUMN id { int | bigint | smallint}
GENERATED { BY DEFAULT | ALWAYS } AS IDENTITY PRIMARY KEY;
For an explanation of identity columns, see https://blog.2ndquadrant.com/postgresql-10-identity-columns/.
For the difference between GENERATED BY DEFAULT and GENERATED ALWAYS, see https://www.cybertec-postgresql.com/en/sequences-gains-and-pitfalls/.
For altering the sequence, see https://popsql.io/learn-sql/postgresql/how-to-alter-sequence-in-postgresql/.
I landed here because I was looking for something like that too. In my case, I was copying the data from a set of staging tables with many columns into one table while also assigning row ids to the target table. Here is a variant of the above approaches that I used.
I added the serial column at the end of my target table. That way I don't have to have a placeholder for it in the Insert statement. Then a simple select * into the target table auto populated this column. Here are the two SQL statements that I used on PostgreSQL 9.6.4.
ALTER TABLE target ADD COLUMN some_column SERIAL;
INSERT INTO target SELECT * from source;
ALTER TABLE test1 ADD id int8 NOT NULL GENERATED ALWAYS AS IDENTITY;

incorrect data update on Sybase trigger execution

I have a table test_123 with the column as:
int_1 (int),
datetime_1 (datetime),
tinyint_1 (tinyint),
datetime_2 (datetime)
So when column datetime_1 is updated and the value at column tinyint_1 = 1 that time i have to update my column datetime_2 with column value of datetime_1
I have created the below trigger for this.. but with my trigger it is updating all datetime2 column values with datetime_1 column when tinyint_1 = 1 .. but i just want to update that particular row where datetime_1 value has updated( i mean changed)..
Below is the trigger..
CREATE TRIGGER test_trigger_upd
ON test_123
FOR UPDATE
AS
FOR EACH STATEMENT
IF UPDATE(datetime_1)
BEGIN
UPDATE test_123
SET test_123.datetime_2 = inserted.datetime_1
WHERE test_123.tinyint_1 = 1
END
ROW-level triggers are not supported in ASE. There are only after-statement triggers.
As commented earlier, the problem you're facing is that you need to be able to link the rows in the 'inserted' pseudo-table to the base table itself. You can only do that if there is a key -- meaning: a column that uniquely identifies a row, or a combination of columns that does so. Without that, you simply cannot identify the row that needs to be updated, since there may be multiple rows with identical column values if uniqueness is not guaranteed.
(and on a side note: not having a key in a table is bad design practice -- and this problem is one of the many reasons why).
A simple solution is to add an identity column to the table, e.g.
ALTER TABLE test_123 ADD idcol INT IDENTITY NOT NULL
You can then add a predicate 'test_123.idcol = inserted.idcol' to the trigger join.

How to AUTO_INCREMENT in db2?

I thought this would be simple, but I can't seem to use AUTO_INCREMENT in my db2 database. I did some searching and people seem to be using "Generated by Default", but this doesn't work for me.
If it helps, here's the table I want to create with the sid being auto incremented.
create table student(
sid integer NOT NULL <auto increment?>
sname varchar(30),
PRIMARY KEY (sid)
);
Any pointers are appreciated.
You're looking for is called an IDENTITY column:
create table student (
sid integer not null GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1)
,sname varchar(30)
,PRIMARY KEY (sid)
);
A sequence is another option for doing this, but you need to determine which one is proper for your particular situation. Read this for more information comparing sequences to identity columns.
You will have to create an auto-increment field with the sequence object (this object generates a number sequence).
Use the following CREATE SEQUENCE syntax:
CREATE SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10
The code above creates a sequence object called seq_person, that starts with 1 and will increment by 1. It will also cache up to 10 values for performance. The cache option specifies how many sequence values will be stored in memory for faster access.
To insert a new record into the "Persons" table, we will have to use the nextval function (this function retrieves the next value from seq_person sequence):
INSERT INTO Persons (P_Id,FirstName,LastName)
VALUES (seq_person.nextval,'Lars','Monsen')
The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would be assigned the next number from the seq_person sequence. The "FirstName" column would be set to "Lars" and the "LastName" column would be set to "Monsen".
hi If you are still not able to make column as AUTO_INCREMENT while creating table. As a work around first create table that is:
create table student(
sid integer NOT NULL
sname varchar(30),
PRIMARY KEY (sid)
);
and then explicitly try to alter column bu using the following
alter table student alter column sid set GENERATED BY DEFAULT AS
IDENTITY
Or
alter table student alter column sid set GENERATED BY DEFAULT
AS IDENTITY (start with 100)
Added a few optional parameters for creating "future safe" sequences.
CREATE SEQUENCE <NAME>
START WITH 1
INCREMENT BY 1
NO MAXVALUE
NO CYCLE
CACHE 10;

DB2 iSeries Trigger for added & modified timestamp and user fields

Perhaps triggers are not needed for added/modifed dates, maybe there are appropriate functions to set their values, in any case:
My question is with the following fields,
created (timestamp)
updated (timestamp)
createdBy (string, to hold the created by user name)
updatedBy (string, to hold the updated by user name)
how do I alter the table such that on creation and update these fields hold the appropriate values?
Edit: I now just need to know how to set the updatedBy and updated timestamp fields each time the record is accessed.
Create the following table for a reference:
create table test(
id integer generated always as identity,
content char(60),
createdBy char(30) default user,
created timestamp default current timestamp,
updatedBy char(30),
updated timestamp default null,
primary key(id)
)
This table has an auto incrementing primary key (id), a createdBy field which is set on insert, a created timestamp which is set on insert now we just need triggers to make the last two work as expected (there is a new feature to set updated on update without the use of triggers but the feature does not seem to allow a null value to show the record has never been updated so that does not work for me).
insert into test (content) VALUES ('first thing'),
('second thing')
To see that the default values for created and createdBy have been set:
select * from test
To add update triggers:
CREATE TRIGGER mytrigger
NO CASCADE BEFORE UPDATE ON test
REFERENCING NEW AS post
FOR EACH ROW MODE DB2ROW
SET
post.updated = CURRENT TIMESTAMP,
post.updatedBy = USER
To see if the above is working, lets update the values in "content":
update co05arh/test
set content = 'first thing updated'
where id = 1
To see the new default values
select * from co05arh/test
We should then see something like
ID CONTENT CREATEDBY CREATED UPDATEDBY UPDATED
1 first thing updated KEN 2011-04-29 16:16:17.942429 KEN 2011-04-29 16:16:28.649543
2 second thing KEN 2011-04-29 16:16:18.01629 <null> <null>