I\'m using PostgreSQL and am an SQL beginner. I\'m trying to create a table from a query, and if I run:
CREATE TABLE table_name AS
(....query...)
<
If you are going to write a function for this, base it on system catalog table pg_class, not on views in the information schema or the statistics collector (which only exist if activated).
CREATE OR REPLACE FUNCTION create_table_qry(_tbl text
, _qry text
, _schema text = NULL)
RETURNS bool AS
$func$
DECLARE
_sch text := COALESCE(_schema, current_schema());
BEGIN
IF EXISTS (
SELECT 1
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = _sch
AND c.relname = _tbl
) THEN
RAISE NOTICE 'Name is not free: %.%',_sch, _tbl;
RETURN FALSE;
ELSE
EXECUTE format('CREATE TABLE %I.%I AS %s', _sch, _tbl, _qry);
RAISE NOTICE 'Table created successfully: %.%',_sch, _tbl;
RETURN TRUE;
END IF;
END
$func$ LANGUAGE plpgsql;
The function takes a table name and the query string, and optionally also a schema to create the table in (defaults to the current schema).
Note the correct use of = in the function header and := in the function body:
Also note how identifiers are escaped as identifiers. You can't use regclass, since the table does not exist, yet: