Get the search result field when you do not have a row

advertisements

Let's explain better:

I need update a table only if some condition is true.

When the condition is true, the update occurs, and I get back the updated fields and the id of row updated with returning key.

The problem is when the condition is not satisfied, so the update does not occurs and my resultset is empty...

You can simulate by these scripts:

create table wn_liberacao (

  id serial not null primary key,
  data_inicial date,
  data_final date,
  consulta_limite integer not null,
  consulta_utilizada integer not null

);

and

insert into
  wn_liberacao ( data_inicial, data_final, consulta_limite, consulta_utilizada )
        values ( '2015-01-01', '2020-12-31', 10, 0 );

so, when you run this query:

with liberado as (

update wn_liberacao
   set consulta_utilizada = 1 + consulta_utilizada
  from ( select id from wn_liberacao where ( data_inicial <= current_date ) and ( data_final >= current_date ) and ( consulta_limite > consulta_utilizada )
--         and 1=2
       ) liberacao
 where liberacao.id = wn_liberacao.id

returning wn_liberacao.id id_liberacao, wn_liberacao.consulta_limite, wn_liberacao.consulta_utilizada

) 

select
  case liberado.id_liberacao
    when null then 'NOT' --0
    else 'YES' --1
  end liberou, liberado.*
  from liberado

the 10 first times that this query runs, I receive YES.... but the 11th time, the result is nulll, no row of data....

I need after 11th time, the result was 'NOT' for the 'liberou' field, and the other fields can be null...

How can I do that???


select true as liberou, liberado.*
from liberado
union all
select false, null, null, null

order by liberou desc
limit 1

false orders before true so if there is A returning row the 'true' row will be returned otherwise the false row will be returned.