we usually create view is it feasible to insert or update on views instead of table lets explore.
point to note that if insert succeed on view then data essentially got inserted into table only.
case simple view:
create new view as follows
create view vw_15
as
select * from book where id <=15
attempt an insert
insert into vw_15(title,author) values('my book','test')
Output:
INSERT 0 1
Query returned successfully in 235 msec.
Inference : insert got succeeded
Case view with computed column
First we will create a view as follows
create view vw_lw_author
as
select title,lower(author) as author from book
try to insert into view
insert into vw_lw_author(title,author) values('my book','SANGRAM')
Output:
ERROR: cannot insert into column "author" of view "vw_lw_author"
DETAIL: View columns that are not columns of their base relation are not updatable.
SQL state: 0A000
Inference : insert failed
Case view with check option
create view vw_15_check
as
select * from book where id <=15 with check option
try to insert here
insert into vw_15_check(title,author) values('my book','SANGRAM')
or
insert into vw_lw_author(title,author) values('my book','sangram')
Output:
ERROR: new row violates check option for view "vw_15_check"
DETAIL: Failing row contains (20, my book, SANGRAM, null, null, null, null).
SQL state: 44000
Inference : insert failed
Updating with check option column
our view
create view vw_price_lte_200
as
select * from public."Movies" where "Price" <=200 with check option
we try to update
update vw_price_lte_200 set "Price" = 150
output:
UPDATE 1
Query returned successfully in 106 msec.
Here update succeed
Now try update that violate constraint
update vw_price_lte_200 set "Price" = 600
Output:
ERROR: new row violates check option for view "vw_price_lte_200"
Here update fails.
DETAIL: Failing row contains (5, Sholay, 2019-10-10, Action, 600).
SQL state: 44000
No comments:
Post a Comment