How to do if in sql - Postgres

Asked

Viewed 493 times

0

Need to do an if in the example postgres.

SELECT
log."data" AS log_data,
log."tipomovimento" AS log_tipomovimento,
     log."nomefornecedor" AS log_nomefornecedor,
     log."nomeproduto" AS log_nomeproduto
FROM
"public"."log" log
WHERE
     if(log."nomefornecedor" != null) {
 log."data" BETWEEN '2018-01-01' and '2018-06-30'
     and log."tipomovimento" IN ('S') and
    "nomefornecedor" = 'x';
}else{
log."data" BETWEEN '2018-01-01' and '2018-06-30'
     and log."tipomovimento" IN ('S') 
}

If the supplier is not null it will filter supplier, if it is null it will not filter supplier on Where. Would anyone have any idea ?

2 answers

2

No need for IF, use OR:

where log."data" BETWEEN '2018-01-01' and '2018-06-30'
and log."tipomovimento" IN ('S') 
and (log."nomefornecedor" = null OR "nomefornecedor" = 'x')

1


The way it is in the question, you don’t need to use if or case. @Lisângelo Berti’s answer solves your problem.

You do not need to check that the value of a column is null, and then apply a filter. The filter is to precisely filter the value of that column.

The correct use would look something like this: The user informs the parameter to filter as null. If it is null, returns all names, if the filter does not apply that column.

Example:

WHERE log."data" BETWEEN '2018-01-01' and '2018-06-30' 
and log."tipomovimento" IN ('S')
and 
(case when [parametro] is null then 
    1=1
else
    log."nomefornecedor" = [parametro];
end)
  • 1

    Very good, it worked for me, thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.