dslreports logo
 
    All Forums Hot Topics Gallery
spc
Search similar:


uniqs
7394

Nordy
join:2007-10-20

Nordy

Member

mySql return selected fields in select when using if exists

When using if exists with a select, how can I get it to return the id or what ever field or fields I want it to display, or 'Does not exist'?

SELECT IF(EXISTS( SELECT id, dateIn FROM table WHERE id = 10), my selected fields here, 'Does not exist')
 

Or is there's another way to do this?

cowboyro
Premium Member
join:2000-10-11
CT

cowboyro

Premium Member

select
case when id is not null then id else 'n/a' end as id,
case when datein is not null then datein else 'n/a' as datein
from mytable
where...

Nordy
join:2007-10-20

Nordy

Member

id will not be NULL. If it doesn't exist, it's just blank. Can something like this be done?
select
case when exists (id) then id else 'n/a' end as id
from mytable
where id="35";
 

hairspring
join:2007-11-23
Oakville, ON

4 edits

hairspring

Member

Exists requires a subquery, which you have, but a blank will be considered a value so exists will always be true on blanks. Think of 'exists' as 'there is a row matching the criteria'. To map blanks/nulls to user friendly values, you will need to use CASE or COALESCE.

2 options:

SELECT
  CASE
    WHEN id = '' THEN 'n/a'
    ELSE id
  END
FROM mytable;
 

or

SELECT
   COALESCE(NULLIF(id,''), 'n/a') AS 'id'
FROM mytable;
 

**edits... brain farts on code blocks.

Nordy
join:2007-10-20

Nordy

Member

So I did:
SELECT
  CASE
    WHEN id = '' THEN 'n/a'
    ELSE id
  END
FROM mytable where id = 10;
 
If id exists all is fine, but if not I don's see 'n/a'

hairspring
join:2007-11-23
Oakville, ON

hairspring

Member

is there a row with id=10?

Nordy
join:2007-10-20

Nordy

Member

Yes there is. It works fine if a row exists. If there isn't one I don't get the 'N/A' message. That's the strangest part.

cowboyro
Premium Member
join:2000-10-11
CT

cowboyro

Premium Member

I didn't realize it's the ID field itself where you put the condition - in such a case it would only return that id and nothing else (no null, no blank).
It might be easier to use a subquery/temp table to make the decision

declare @resultstbl table (id varchar, datein datetime)
declare @numrecords int
insert into @resultstbl (id, datein) select id, datein from mytable where...
select @numrecords = count(*) from @resultstbl
if @numrecords>0
select id, datein from @resultstbl
else
select 'no record' as id, 'n/a' as datein