Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add primary key to View?

Tags:

I have a view and want to make one attribute a primary key.

CREATE VIEW filedata_view AS SELECT num PRIMARY KEY, id, ST_TRANSFORM(the_geom,900913) AS the_geom FROM filedata 

But get a error

ERROR:  syntax error at or near "PRIMARY" LINE 2: AS SELECT num PRIMARY KEY, id, ST_TRANSFORM(the_geom,900913)... 

How to do this?

like image 217
Kliver Max Avatar asked Jul 26 '12 10:07

Kliver Max


People also ask

Can I add a primary key to a view?

You cannot create a primary key on a view.

Can we create primary key on view in Oracle?

You can specify only unique, primary key, and foreign key constraints on views. However, you can define the view using the WITH CHECK OPTION clause, which is equivalent to specifying a check constraint for the view. View constraints are supported only in DISABLE NOVALIDATE mode. You cannot specify any other mode.

Can a view have a primary key Postgres?

Views in Postgresql can't have primary keys. You can specify only unique, primary key, and foreign key constraints on views, and they are supported only in DISABLE NOVALIDATE mode.


1 Answers

Views in Postgresql can't have primary keys.

you are basically on wrong way creating constraint on a View, constraints should be created on tables, but some DBMSes do support adding constraints on Views like oracle with this syntax:

ALTER VIEW VIEW_NAME ADD PRIMARY KEY PK_VIEW_NAME DISABLE NOVALIDATE; 

Oracle Doc For Constraints

You can specify only unique, primary key, and foreign key constraints on views, and they are supported only in DISABLE NOVALIDATE mode.

so they only support it for compatibility, if you want to have a primary key to stop insertion of duplicate data in column num in filedata table, you should do it by altering the filedata table and add a primary key on it or by creating your table with primary key on column num from the start.

like image 172
hmmftg Avatar answered Oct 11 '22 11:10

hmmftg