Hi,
I was wondering if anyone could help me improve a SQLite query.
I have a table with a nullable column. Sometimes I want to run a SQL query with a value for the nullable column, and sometimes I run the query without a value. Given the size and complexity of the query that I am writing, I'd like to re-use the same SQL for both queries.
A primitive example follows.
Select all query
returns
Select query with alt_name value
returns
When I was writing the query to get rows without specify a value for the alt_name column, I thought that I could use the IFNULL function and give a value.
Unfortunately, this does not return any results. However, if I give the column an alias that is different from the name of the column, this does work.
Is there a way to write the query so that I do not have to use a column alias but the query can still be reused for both not null and null values for the alt_name column?
Thanks,
Jon
I was wondering if anyone could help me improve a SQLite query.
I have a table with a nullable column. Sometimes I want to run a SQL query with a value for the nullable column, and sometimes I run the query without a value. Given the size and complexity of the query that I am writing, I'd like to re-use the same SQL for both queries.
A primitive example follows.
Code:
CREATE TABLE product (
'_id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
'name' TEXT NOT NULL,
'alt_name' TEXT
)
Code:
INSERT INTO product ('name','alt_name') VALUES ('A','Fred')
INSERT INTO product ('name','alt_name') VALUES ('B',NULL)
Select all query
Code:
SELECT
name,
alt_name
FROM
product
returns
name | alt_name
A | Fred
B | NULL
Select query with alt_name value
Code:
SELECT
name,
alt_name
FROM
product
WHERE alt_name='Fred'
returns
name | alt_name
A | Fred
When I was writing the query to get rows without specify a value for the alt_name column, I thought that I could use the IFNULL function and give a value.
Code:
SELECT
name,
IFNULL(alt_name, 'null') as alt_name
FROM
product
WHERE alt_name='null'
Unfortunately, this does not return any results. However, if I give the column an alias that is different from the name of the column, this does work.
Code:
SELECT
name,
IFNULL(alt_name, 'null') as alt_name_ifnull
FROM
product
WHERE alt_name_ifnull='null'
name | alt_name
B | NULL
Is there a way to write the query so that I do not have to use a column alias but the query can still be reused for both not null and null values for the alt_name column?
Thanks,
Jon