Ellis Valentiner
Ellis Valentiner

Reputation: 2206

Perform query using tables and columns from information_schema

I'm trying to using information_schema.columns to find all of the columns in my database that has a geometry type and then check the SRID for the data in those columns.

I can do this with multiple queries where I first find the table names and column names

SELECT table_name, column_name
FROM information_schema.columns
WHERE udt_name = 'geometry';

and then (manually)

SELECT ST_SRID(column_name)
FROM table_name;

for each entry.

Does anyone how to streamline this into a single query?

Upvotes: 3

Views: 1147

Answers (1)

Nick Barnes
Nick Barnes

Reputation: 21356

Table names can't be variable; Postgres needs to be able to come up with an execution plan before it knows the parameter values. So you can't do this in a simple SQL statement.

Instead, you need to construct a dynamic query string using a procedural language like PL/pgSQL:

CREATE FUNCTION SRIDs() RETURNS TABLE (
  tablename TEXT,
  columnname TEXT,
  srid INTEGER
) AS $$
BEGIN
  FOR tablename, columnname IN (
    SELECT table_name, column_name
    FROM information_schema.columns
    WHERE udt_name = 'geometry'
  )
  LOOP
    EXECUTE format(
      'SELECT ST_SRID(%s) FROM %s',
      columnname, tablename
    ) INTO srid;
    RETURN NEXT;
  END LOOP;
END
$$
LANGUAGE plpgsql;

SELECT * FROM SRIDs();

Upvotes: 2

Related Questions