1

I am very new to postgresql. I want to create a temp table containing some values and empty columns. Here is my query but it is not executing, but gives an error at , (comma).

CREATE TEMP TABLE temp1 
AS (
 SELECT distinct region_name, country_name 
 from opens 
 where track_id=42, count int)

What did I do wrong?

How to create a temp table with some columns that has values using select query and other columns as empty?

3 Answers 3

8

Just select a NULL value:

CREATE TEMP TABLE temp1 
AS
SELECT distinct region_name, country_name, null::integer as "count"
from opens 
where track_id=42;

The cast to an integer (null::integer) is necessary, otherwise Postgres wouldn't know what data type to use for the additional column. If you want to supply a different value you can of course use e.g. 42 as "count" instead

Note that count is a reserved keyword, so you have to use double quotes if you want to use it as an identifier. It would however be better to find a different name.

There is also no need to put the SELECT statement for an CREATE TABLE AS SELECT between parentheses.

Sign up to request clarification or add additional context in comments.

Comments

1

Your error comes form your statement near the clause WHERE.

This should work :

CREATE TEMP TABLE temp1 AS 
(SELECT distinct region_name, 
        country_name,
        0 as count 
 FROM   opens 
 WHERE track_id=42)

Comments

1

Try This.

            CREATE TEMP TABLE temp1 AS 
            (SELECT distinct region_name, 
                    country_name,
                    cast( '0' as integer) as count
             FROM   opens 
             WHERE track_id=42);

2 Comments

cast( '0' as integer) can be simplified to 0
Yes. IT can be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.