Search code examples
postgresqlcreate-table

Create table from query result when it isn't null


I want to create a table from a select query in PostgreSQL using "SELECT table myTable As SELECT...". The problem is it always creates a table even the query returns null. I know I can use of "SELECT Exist(select 1 from myTable)" to determine if the table is empty or not. My question is that can I combine this two SQL commands to one query that checks if the result is not null then create the table.


Solution

  • You can try using the following PL/SQL:

    DO
    $do$
    BEGIN
    IF EXISTS (SELECT 1 FROM some_table) THEN
        SELECT your_table AS SELECT * FROM some_table
    END IF;
    END
    $do$
    

    Note that you need put the above IF statement into a DO block as I have done, or into a function; it won't work if executed directly from pgAdmin.