Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite syntax for If Else condition

Tags:

sql

sqlite

I am using SQLite database. My table has a text column called "Password". Earlier for retrieving the values I used to execute a simple select * from myTable query. But now the requirement is that if Password value is not NULL then I need to show it as "Yes" or otherwise "No". It's something like:

select * from myTable if Password != NULL then Password = 'Yes' else Password = 'No' 

I searched a lot regarding this but I didn't get any proper link or example. Any help or suggestion would be really appreciated.

like image 394
Satya Prakash Panigrahi Avatar asked Jan 29 '13 10:01

Satya Prakash Panigrahi


People also ask

How do you do if else in SQLite?

If the result is true , the IIF() function returns the value of the second expression ( true_expression ). Otherwise, it returns the value of the third expression ( false_expression ). In practice, you use the IIF() function to add the if-else logic to queries to form more flexible queries.

Where multiple conditions SQLite?

The AND operator allows the existence of multiple conditions in a SQLite statement's WHERE clause. While using AND operator, complete condition will be assumed true when all the conditions are true. For example, [condition1] AND [condition2] will be true only when both condition1 and condition2 are true.

Does SQLite support case statement?

SQLite provides two forms of the CASE expression: simple CASE and searched CASE .


2 Answers

SELECT *,        CASE WHEN Password IS NOT NULL        THEN 'Yes'        ELSE 'No'        END AS PasswordPresent FROM myTable 
like image 51
CL. Avatar answered Sep 28 '22 23:09

CL.


SQLite uses the CASE WHEN THEN END syntax. You can read more about that here: http://www.sqlite.org/lang_expr.html

I have not checked the syntax but I'm guessing something like this:

select *  from myTable CASE WHEN Password != NULL THEN Password = 'Yes' ELSE Password = 'No' END; 

Though I'm not sure that would work at all. If you're trying to get a YES or NO based on the presence of a password in the table for every record, perhaps this is closer to what you want:

SELECT Field1,      Field2,     (CASE WHEN Password != NULL THEN          'Yes'       ELSE          'No'       END) as 'Password' FROM myTable; 

Again, I do not currently have access to SQLite to test this myself so it probably needs some work.

like image 42
Nick Avatar answered Sep 28 '22 23:09

Nick