Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IF-THEN-ELSE statements in postgresql

Tags:

sql

postgresql

I'm looking to write a postgresql query to do the following :

if(field1 > 0,  field2 / field1 , 0) 

I've tried this query, but it's not working

if (field1 > 0) then return field2 / field1 as field3 else return 0 as field3 

thank youu

like image 570
user2311028 Avatar asked Sep 26 '13 13:09

user2311028


People also ask

Can we use if-else in PostgreSQL?

In Postgresql, we can use if-else in the select statement but in the place of IF, here we will use the CASE and WHEN that is similar to the if-else statement. Because, in a SELECT statement, we cannot use the IF directly.

What is the correct syntax of writing if/then statement in PL pgSQL?

The IF statement is part of the default procedural language PL/pgSQL. You need to create a function or execute an ad-hoc statement with the DO command. You need a semicolon ( ; ) at the end of each statement in plpgsql (except for the final END ). You need END IF; at the end of the IF statement.

How many types of conditional statements are present in PG Plsql?

PL/pgSQL provides you with three forms of the if statements.

What is $$ in Postgres?

In PostgreSQL, the dollar-quoted string constants ($$) is used in user-defined functions and stored procedures. In PostgreSQL, you use single quotes for a string constant like this: select 'String constant'; When a string constant contains a single quote ('), you need to escape it by doubling up the single quote.


1 Answers

As stated in PostgreSQL docs here:

The SQL CASE expression is a generic conditional expression, similar to if/else statements in other programming languages.

Code snippet specifically answering your question:

SELECT field1, field2,   CASE     WHEN field1>0 THEN field2/field1     ELSE 0   END    AS field3 FROM test 
like image 97
Joseph Victor Zammit Avatar answered Sep 25 '22 14:09

Joseph Victor Zammit