Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ALTER a view in PostgreSQL

PostgreSQL does not allow altering a view (i.e. adding column, changing column orders, adding criterie etc.) if it has dependent objects. This is really getting annoying since you have to write a script to:

  1. Drop all the dependent objects,
  2. Alter the view,
  3. Recreate all the dependent objects back again.

I understand that postgreSQL developers have very reasonable concerns to prevent altering views. But do you guys have any scripts/shot-cuts to do all those manual stuff in a single run?

like image 820
mevdiven Avatar asked Aug 29 '10 04:08

mevdiven


People also ask

Can you alter view in PostgreSQL?

Similarly, you can alter PostgreSQL views. The flow is the same: click New SQL, enter the required CREATE OR REPLACE VIEW or ALTER VIEW query, and click Execute.

Can a view be altered?

If you remember the CREATE VIEW SQL syntax, a view can be modified by simply using the ALTER VIEW keyword instead, and then changing the structure of the SELECT statement. Therefore, let's change the previously created view with the CREATE VIEW SQL statement by using the ALTER VIEW statement.

How do you edit views in Pgadmin?

To view or modify data, right click on a table or view name in the Browser tree control. When the context menu opens, use the View/Edit Data menu to specify the number of rows you would like to display in the editor panel. To modify the content of a table, each row in the table must be uniquely identifiable.

Can we add a column to a view in PostgreSQL?

To add a new column to a PostgreSQL table, the ALTER TABLE command is used with the following syntax: ALTER TABLE table-name ADD new-column-name column-definition; The table-name is the name of the table to be modified. The new-column-name is the name of the new column to be added.


2 Answers

Adding new columns isn't a problem, changing datatypes or changing the order of the columns, that's where you get problems.

  1. Don't change the order, it's not that important anyway, just change your query:

    SELECT a, b FROM view_name;

    SELECT b, a FROM view_name;

  2. When you have to change a datatype of a column, you have to check the depend objects as well. These might have problems with this new datatype. Just get the definition of this object and recreate after the changes. The information_schema and pg_catalog help you out.

  3. Make all changes within a single transaction.
like image 140
Frank Heikens Avatar answered Oct 24 '22 20:10

Frank Heikens


If I place a addtional "drop view xyz; commit;" before the "create or replace view xyz as ..." statement, at least in many cases I resolve the blocking problem described above.

like image 43
Hartmut Pfarr Avatar answered Oct 24 '22 21:10

Hartmut Pfarr