EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PostgreSQL Tutorial PostgreSQL if else
Secondary Sidebar
PostgreSQL Tutorial
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • Postgres Command-Line
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL BIGINT
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Operators
    • PostgreSQL IN Operator
    • Postgres like query
    • PostgreSQL encode
    • PostgreSQL Cheat Sheet
    • PostgreSQL List Databases
    • PostgreSQL Rename Database
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • Joins
    • Joins in PostgreSQL
    • PostgreSQL Inner Join
    • PostgreSQL Outer Join
    • LEFT OUTER JOIN in PostgreSQL
    • PostgreSQL FULL OUTER JOIN
    • PostgreSQL LEFT JOIN
    • PostgreSQL Full Join
    • PostgreSQL Cross Join
    • PostgreSQL NATURAL JOIN
    • PostgreSQL UPDATE JOIN
  • Queries
    • PostgreSQL Queries
    • PostgreSQL INSERT INTO
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL ORDER BY Random
    • PostgreSQL ORDER BY DESC
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query
  • Advanced
    • PostgreSQL Schema
    • Postgres List Schemas
    • PostgreSQL Drop Schema
    • PostgreSQL VARCHAR
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL User Password
    • PostgreSQL log_statement
    • PostgreSQL repository
    • PostgreSQL shared_buffer
    • PostgreSQL String Functions
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL String Array
    • PostgreSQL where in array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL CHECK Constraint
    • PostgreSQL INTERSECT
    • PostgreSQL Like
    • Cursors in PostgreSQL
    • PostgreSQL UNION ALL
    • Indexes in PostgreSQL
    • PostgreSQL Index Types
    • PostgreSQL REINDEX
    • PostgreSQL UNIQUE Index
    • PostgreSQL Clustered Index
    • PostgreSQL DROP INDEX
    • PostgreSQL DISTINCT
    • PostgreSQL FETCH
    • PostgreSQL RAISE EXCEPTION
    • PostgreSQL Auto Increment
    • Sequence in PostgreSQL
    • Wildcards in PostgreSQL
    • PostgreSQL Subquery
    • PostgreSQL Alias
    • PostgreSQL LIMIT
    • PostgreSQL Limit Offset
    • PostgreSQL LAG()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL Describe Table
    • PostgreSQL Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • PostgreSQL List Tables
    • PostgreSQL TRUNCATE TABLE
    • PostgreSQL Table Partitioning
    • Postgres DROP Table
    • PostgreSQL Functions
    • PostgreSQL Math Functions
    • PostgreSQL Window Functions
    • Aggregate Functions in PostgreSQL
    • PostgreSQL Primary Key
    • Foreign Key in PostgreSQL
    • PostgreSQL Procedures
    • PostgreSQL Stored Procedures
    • PostgreSQL Views
    • PostgreSQL Materialized Views
    • Postgres Create View
    • PostgreSQL Triggers
    • PostgreSQL DROP TRIGGER
    • PostgreSQL Date Functions
    • PostgreSQL TO_DATE()
    • PostgreSQL datediff
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL LENGTH()
    • PostgreSQL blob
    • PostgreSQL Median
    • PostgreSQL kill query
    • PostgreSQL Formatter
    • PostgreSQL RANK()
    • PostgreSQL Select
    • PostgreSQL Average
    • PostgreSQL DATE_PART()
    • PostgreSQL EXECUTE
    • PostgreSQL COALESCE
    • PostgreSQL EXTRACT()
    • PostgreSQL Sort
    • PostgreSQL TO_CHAR
    • PostgreSQL Interval
    • PostgreSQL Number Types
    • PostgreSQL ROW_NUMBER
    • Alter Column in PostgreSQL
    • PostgreSQL Identity Column
    • PostgreSQL SPLIT_PART()
    • PostgreSQL CONCAT()
    • PostgreSQL replace
    • PostgreSQL TRIM()
    • PostgreSQL MAX
    • PostgreSQL DELETE
    • PostgreSQL Float
    • PostgreSQL OID
    • PostgreSQL log
    • PostgreSQL REGEXP_MATCHES()
    • PostgreSQL MD5 
    • PostgreSQL NOW()
    • PostgreSQL RANDOM
    • PostgreSQL round
    • PostgreSQL Trunc()
    • PostgreSQL TIME
    • PostgreSQL IS NULL
    • PostgreSQL CURRENT_TIME
    • PostgreSQL MOD()
    • Postgresql Count
    • PostgreSQL Datetime
    • PostgreSQL MIN()
    • PostgreSQL age()
    • PostgreSQL enum
    • PostgreSQL OR
    • PostgreSQL Wal
    • PostgreSQL NOT IN
    • PostgreSQL SET
    • PostgreSQL Current Date
    • PostgreSQL Compare Date
    • PostgreSQL SERIAL
    • PostgreSQL UUID
    • PostgreSQL Merge
    • PostgreSQL Database
    • PostgreSQL Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Show Databases
    • PostgreSQL Restore Database
    • PostgreSQL DROP DATABASE
    • PostgreSQL ALTER DATABASE
    • Postgres DROP Database
    • Postgres Dump Database
    • PostgreSQL OFFSET
    • PostgreSQL GRANT
    • PostgreSQL COMMIT
    • PostgreSQL ROLLUP
    • PostgreSQL JSON
    • EXPLAIN ANALYZE in PostgreSQL
    • PostgreSQL Temporary Table
    • PostgreSQL Show Tables
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL Encryption
    • PostgreSQL DECODE()
    • PostgreSQL Vacuum
    • PostgreSQL EXCLUDE
    • Postgres Change Password
    • Postgres Delete Cascade
    • PostgreSQL EXCEPT
    • PostgreSQL Roles
    • PostgreSQL Link
    • PostgreSQL Partition
    • PostgreSQL column does not exist
    • PostgreSQL Log Queries
    • PostgreSQL escape single quote
    • PostgreSQL Query Optimization
    • PostgreSQL Character Varying
    • PostgreSQL Transaction
    • PostgreSQL Extensions
    • PostgreSQL Import CSV
    • PostgreSQL Client
    • PostgreSQL caching
    • PostgreSQL Incremental Backup
    • PostgreSQL JSON vs JSONNB
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions

PostgreSQL if else

By Payal UdhaniPayal Udhani

PostgreSQL if else

Introduction to PostgreSQL if else

Using the queries will give control of the database and allow the user to manipulate it effectively and strongly in any SQL or database language. Some statements help the user have better control over the queries and help in decision-making based on PostgreSQL conditions; these statements are called the control statements. One of the most crucial and powerful out of all of them is the if-else statement. This statement allows us to execute certain code only when some condition is fulfilled. If not, then some other code might be executed.

Syntax:

Format 1:

IF condition THEN
-- code or statements to be executed
END IF;

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Format 2:

IF condition THEN
-- code or statements to be executed
ELSE
-- code or statements to be executed
END IF;

Format 3:

IF condition THEN
-- code or statements to be executed
ELSE IF THEN
-- code or statements to be executed
ELSE
-- code or statements to be executed
END IF;

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,294 ratings)

We can use only if the statement if we want to execute certain statements on fulfilment of some condition, or we can use the second format where the control when the condition evaluates to true and when it evaluates to false is given can execute our statements accordingly. The nesting if inside else of another if is also possible. This is a completely customisable structure and can be used as per our convenience and requirement.

Examples of PostgreSQL if else

Given below are the examples:

Example #1

In our first example, we will consider two variables and then, using the format 1 mentioned above; we will write the statements in such a way that when the variable1 is less than or greater than or equal to variable2, then an appropriate message with the notice will be raised after they are compared using comparing operators. Here, three separate if statements will be used to achieve our use-case requirement.

Code:

DO $$
DECLARE
variable1 integer := 55;
variable2 integer := 75;
BEGIN
IF variable1 > variable2 THEN
RAISE NOTICE 'variable1 is greater than variable2 ';
END IF;
IF variable1 < variable2 THEN
RAISE NOTICE 'variable1 is less than variable2 ';
END IF;
IF variable1 = variable2 THEN
RAISE NOTICE 'variable1 is exactly equal to variable2 ';
END IF;
END $$;

Output:

PostgreSQL if else 1

As you can see, as 55 is less than 75, the message saying variable1 is less than variable2 is displayed. This was achieved only by using the simple if statement.

Example #2

Let us now consider the same example as of example 1 but using the format2 for performing the operations. Format 2 contains a simple if, and if the condition evaluates to false, then the else block will be executed. Considering two variables variable1 and variable2, we will compare if variable 1 is greater than variable2 if the condition evaluates to true, then notice saying variable1 is greater than variable2 will be raised; if not, statements in else block will get executed, and appropriate notice will be raised over there.

Code:

DO $$
DECLARE
variable1 integer := 49;
variable2 integer := 50;
BEGIN
IF variable1 > variable2 THEN
RAISE NOTICE 'variable1 is greater than variable2';
ELSE
RAISE NOTICE 'variable1 is not greater than variable2';
END IF;
END $$;

Output:

PostgreSQL if else 2JPG

As we can see, here we can’t check for the equal condition. Even when both the variables are equal, then the message will be displayed saying variable1 is not greater than variable2, which means it can be small or equal. This problem is overcome using the format3 of if-else, where we can do nesting of other if-else or if statements inside the original ones up to any level as per our convenience.

Example #3

Now, we will use format3 to implement the same use case scenario as of example1 and example2 and apply the most compact and appropriate solution for this use case of number comparison.

Code:

DO $$
DECLARE
variable1 integer := 98;
variable2 integer := 100;
BEGIN
IF variable1 > variable2 THEN
RAISE NOTICE 'variable1 is greater than b';
ELSIF variable1 < variable2 THEN
RAISE NOTICE 'variable1 is less than b';
ELSE
RAISE NOTICE 'variable1 is equal to b';
END IF;
END $$;

Firstly, variable1 is greater than variable2 condition will be checked and if not then it will go to else if block, where less than condition will be checked and if both conditions evaluate to false then message with a notice saying both are equal, will be raised.

Output:

It will be as follows when variable1 and variable2 have 98 and 100 values, respectively.

variable1 and variable2 will have 98 and 100 values

Example #4

Let us now see an example where these conditions are most often used, that is, using query results for condition specification. We have one table in my database named educational_platforms whose description is as follows using the below command-

Code:

\d educational_platforms;

Output:

\d educational_platforms;

You can create one if it’s not there. Let us see the contents of the table.

Code:

select * from educational_platforms;

Output:

PostgreSQL if else 5JPG

If an entry with psql technology exists, we have to update the client count of that entry to 100; else, insert the record with psql technology. Here are the statements that will do so.

Code:

DO $$
BEGIN
IF EXISTS (SELECT FROM educational_platforms WHERE technology='psql') THEN
UPDATE educational_platforms SET clientcount=101 WHERE technology='psql';
ELSE
insert into educational_platforms values (3,'psql',80,101,'RDBMS','');
END IF;
END $$;

Output:

PostgreSQL if else 6JPG

Let us check the contents of the table again.

Code:

select * from educational_platforms;

Output:

from educational platform

Conclusion

We can use if, if-else and nested if-else statements in our PostgreSQL database as per our convenience to achieve our use-case requirement. We can use these conditional statements in functions, stored procedures, variables, query statements, or inside the loop statements wherever we want to check the conditions and, based on the output of that condition, execute some statements.

Recommended Articles

This is a guide to PostgreSQL if-else. Here we discuss the introduction to PostgreSQL if-else along with respective examples for better understanding. You may also have a look at the following articles to learn more –

  1. PostgreSQL Triggers
  2. PostgreSQL Administration
  3. PostgreSQL Alias
  4. PostgreSQL LAG()
  5. Guide to PostgreSQL NOW()
  6. PostgreSQL RANDOM | Examples
  7. Guide to PostgreSQL Queries
Popular Course in this category
PostgreSQL Course (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |  7+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more