Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a null row in Postgres in a generic manner

Tags:

sql

postgresql

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?

like image 565
Tom Ellis Avatar asked May 14 '13 08:05

Tom Ellis


People also ask

How do I use null in PostgreSQL?

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.

Can we insert null in foreign key column PostgreSQL?

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.

Can we insert null in integer column in PostgreSQL?

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 .

What is NVL in PostgreSQL?

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.


2 Answers

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?

like image 105
mvp Avatar answered Sep 27 '22 17:09

mvp


Just abuse an outer join like so:

select col1, col2 from foo 
full join (select) as dummy on false
like image 21
usethe4ce Avatar answered Sep 27 '22 19:09

usethe4ce