Postgresql – Having Updatable Views that obey initial select conditions

postgresql

Let's say I have a table like this:

+--------------+----------+-------------+
| name         | is       | in          |
|--------------+----------+-------------|
| Study        | <null>   | <null>      |
| Sport        | <null>   | <null>      |
| Biology      | Study    | <null>      |
| Linguistics  | Study    | <null>      |
| Art          | <null>   | <null>      |
+--------------+----------+-------------+

And I want to build a view as such:

CREATE VIEW v AS SELECT name FROM t WHERE "is" = 'Study';

Now if I want to insert into this view, it does not automatically set "is" to 'Study', I have to write a trigger and a function to adjust this behavior. However, this is a highly repeated pattern in my application, and I was wondering if there is a way to automatically achieve this (an updatable view that obeys the select condition).

Best Answer

maybe it works, it is in SQL server but concept maybe the same in your case:

If its always required you can set default. It will update always when you insert the view [is] with 'Study':

ALTER TABLE t ADD CONSTRAINT  df_is DEFAULT 'Study' FOR [is];

Or you can create another view only for insert:

CREATE VIEW v_insert AS SELECT name,[is] FROM t WHERE [is] = 'Study';
DECLARE @is NVARCHAR(max)='Study';
INSERT INTO dbo.v_insert (name, [is]) VALUES ('nametoinsert', @is )