sandeep rawat
sandeep rawat

Reputation: 4957

How to select one row if condition true, all rows if condition false in sql?

Suppose there is a table

temp

col1 | col ----

100 | c

456 | c1

131 |c2

--

suppose I have coll1 = 100 means a valid row query have to return only the row
if value does not exists in table query have to return all row from table.

Note: We can not use if exists or any procedural thing (only SQL no TSQL)

We cannot use below

   if exists( select 1 from temp where col1=100)

      begin
         select 1 from temp where col1=100 
     end
  else 
     begin
        select  * from temp where col1=100 
     end

Upvotes: 1

Views: 3746

Answers (2)

sgeddes
sgeddes

Reputation: 62861

You can do this with just using not exists:

SELECT *
FROM temp t
WHERE col1 = 100 
    OR NOT EXISTS (SELECT 1
                   FROM temp 
                   WHERE col1 = 100);

Upvotes: 2

SD433
SD433

Reputation: 119

$qry1="Select Col1 from table where col1=100";
$res1 = mysql_query($qry1);
if(row_count($res)>0){
/* Process data*/
}
else{
$qry2="Select * from table where col1=100";
$res2 = mysql_query($qry2);
/*process data*/
}

Upvotes: 1

Related Questions