When I create a view in PostGIS is there any way to add a unique ID to that view? Just like the "gid" field in any other PostGIS table?
Edit: Sorry I should have included this in the original post. I am using PostGresql 9.0 and PostGIS 1.5.
Ando
You should be able to use the row_number() function as a column in your view. This works for Postgres 8.4 or higher.
http://www.postgresql.org/docs/current/static/functions-window.html
SELECT * FROM
( SELECT
ROW_NUMBER() OVER (ORDER BY column_to_sort_by ASC) AS ROW_NUMBER,
Col1, Col2
FROM table_name
) myview_name
This should work in most databases including SQL Server, Oracle, and MySQL.
row_number() OVER() AS "id"
without ORDER
over column
Commented
Feb 12, 2016 at 17:43
row_number
is effectively a random value. You can't depend on it being consistent between SELECT
s, particularly when the underlying data changes.
For older versions of PostgreSQL (<= 8.3), here is another solution. In this example, I use another column name vid
for "view ID".
First, create a sequence. Use CYCLE
so that it will loop in the event you reach the end of the sequence.
CREATE SEQUENCE myview_vid_seq CYCLE;
Now, create a VIEW that uses the sequence:
CREATE OR REPLACE VIEW myview AS
SELECT nextval('myview_vid_seq'::regclass) AS vid, mytable.*
FROM mytable;