Laura
Laura

Reputation: 2773

SQLITE: Select another column if the first one is null

I want to select the value from another column if there are no records in the first column (is null). I want something like this:

SELECT (if Column1 IS NULL THEN Column2), Column3, Column4 FROM MyTable

How can I do that in SQLite?

Upvotes: 5

Views: 1666

Answers (4)

Preet Sangha
Preet Sangha

Reputation: 65476

From Safari Books

Name

coalesce() — Return first non-NULL argument

Common Usage

coalesce( param1, param2, ... )

Description

The coalesce() function takes two or more parameters and returns the first non-NULL parameter. If all of the parameter values are NULL, a NULL is returned.

See Also

ifnull(), nullif()

Upvotes: 3

AllTooSir
AllTooSir

Reputation: 49362

Use COALESCE(column1,column2) .

SELECT COALESCE(Column1, Column2), Column3, Column4 FROM MyTable

Upvotes: 1

Stephan
Stephan

Reputation: 8090

You can use IFNULL function , try this

SELECT IFNULL(Column1, Column2), Column3, Column4 FROM MyTable

Upvotes: 2

lc.
lc.

Reputation: 116458

Use the COALESCE function, which returns the first non-null argument:

SELECT COALESCE(Column1, Column2), Column3, Column4
FROM MyTable

In this case, you will get Column1 but if it is NULL, Column2 will be returned instead.

Upvotes: 12

Related Questions