7

I would like to do

select col1, col2 from foo union values (null, null)

but null is given the default type of TEXT, so I get the error "UNION types [e.g.] integer and text cannot be matched". In specific cases I can provide the types of the columns of foo, but I am constructing SQL statements programatically and it would be preferable if I didn't have to carry around the column type information with me.

Is there a workaround for this?

4 Answers 4

3

You can query INFORMATION_SCHEMA table COLUMNS using query like this:

SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name = 'mytable'

or you can use PostgreSQL specific form:

SELECT attname, atttypid::regtype
FROM pg_attribute
WHERE attrelid = 'public.mytable'::regclass
  AND attnum > 0

This will give you data types for columns of interest in your table. Having this, in your automated framework you can generate UNION string to add empty row by casting NULLs to required data type, like this:

SELECT col1, col2 FROM foo
UNION ALL VALUES (NULL::VARCHAR, NULL::INTEGER)

Probably more important question is why do you want empty row? Perhaps you can get around without having this synthetic empty row in first place?

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

1 Comment

Thanks mvp. As you say, it's probably best to try to get around it.
2

Just abuse an outer join like so:

select col1, col2 from foo 
full join (select) as dummy on false

Comments

0

If col1 is of type bar and col2 is of type baz then

select col1, col2 from foo union values (null::bar, null::baz)

Will work

1 Comment

That's what Tom is trying to avoid.
0

Actually, you can cast NULL to int, you just can't cast an empty string to int. Assuming you want NULL in the new column if data1 contains an empty string or NULL, you can do something like this:

UPDATE table SET data2 = cast(nullif(data1, '') AS int);

or

UPDATE table SET data2 = nullif(data1, '')::int;

Reference

1 Comment

That doesn't seem to be an answer to the question I asked.

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.