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?
Let's look at an example of how to use PostgreSQL IS NULL in a SELECT statement: SELECT * FROM employees WHERE first_number IS NULL; This PostgreSQL IS NULL example will return all records from the employees table where the first_name contains a NULL value.
A foreign key containing null values cannot match the values of a parent key, since a parent key by definition can have no null values. However, a null foreign key value is always valid, regardless of the value of any of its non-null parts.
An integer column can be null, but '' is an empty string not null. The right syntax for a null integer (or any other sql type) is null .
The NVL function returns the first of its arguments that isn't null. NVL evaluates the first expression. If that expression evaluates to NULL , NVL returns the second expression. NVL(expr1, expr2) The return type is the same as the argument types.
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?
Just abuse an outer join like so:
select col1, col2 from foo
full join (select) as dummy on false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With