If you are using SQL Server you could use case
statement like w0lf mentioned or you could use iif
statement like so:
select iif(age > 21, 'Allowed', 'Not Allowed') as status
from test;
Example:
create table test (
fullname varchar (20),
age int
);
insert into test values
('John', 10),
('Matt', 90),
('Jane', 25),
('Ruby', 80),
('Randy', null);
Result
| fullname | status |
|----------|-------------|
| John | Not Allowed |
| Matt | Allowed |
| Jane | Allowed |
| Ruby | Allowed |
| Randy | Not Allowed |
The same thing can be written as
select case when age > 21 then 'Allowed' else 'Not Allowed' end as status
from test;
case
statement is used by many database engines.
If you are dealing with null and not null values, you could also use coalesce
like so:
select fullname, coalesce(age, 999) as status
from test;
The result will be:
| fullname | status |
|----------|--------|
| John | 10 |
| Matt | 90 |
| Jane | 25 |
| Ruby | 80 |
| Randy | 999 |
At first you may think that coalesce
does if age is null then 999 else age
. It does that, sort-of, but in particular coalesce
outputs the first non-null value in a list. So, coalesce(null, null, 45)
will result in 45. coalesce(null, 33, 45)
will result in 33.
Feel free to play around with SQL Fiddle: http://sqlfiddle.com/#!6/a41a7/6