Is there a way of safe selecting a column that doesn’t exists in a table without geting "invalid identifier" error? Maybe returning null instead?
Something like this:
select
id,
non_existant_column as col_name -- return null here instead of rising an error
from table
I tried already a number of SQL (coalesce, ifnull, …) and dbt (dbt_utils.star, jinja adapter) functions.
I would like to see a simple solution returning null in the column values if the column doesn’t exists.
3
Answers
This is dependent upon the database you’re using, but:
In PostgreSQL:
In short, no, when you run a query against a non-existant resource, it will throw an error. However, there are ways you can work around this.
For example you can run queries against your database to check your schema, however:
A) This has to be run before you run your queries, and
B) I would recommend using a different database engine such as a NoSQL db if you need schema flexibility – schema flexibility is not what relational databases are exactly intended for.
Getting schema information:
An example query using schema information:
This is easy to do in DBT:
Under the hood, this is doing the same thing as Gerik’s answer above. It queries the underlying DB’s information schema at compile time to retrieve the column list which you can use to generate your final SQL.
There is a PostgreSQL way using JSON, not very nice however.
A typecast would be needed for
col_name
expression.In your particular case it would be something like
column_name_x
expressions would need to be typecast. You may also prefer JSONB arrow syntax(jr -> 'non_existent_column_a')
rather than subscripting.