JIYIK CN >

Current Location:Home > Learning > DATABASE > PostgreSQL >

If statement in PostgreSQL

Author:JIYIK Last Updated:2025/04/27 Views:

ifStatement evaluates a condition by returning true or false value. We can use it to perform condition based queries.

This article will teach you how to write ifconditional statements and understand how conditional statements can help you when developing backend applications.

Use the statement to write queries in PostgreSQL ifto perform different operations

Use the following command to log in to the PostgreSQL server. Enter the password in the returned prompt and press Enter.

david@david-HP-ProBook-6470b:~/Documents/work/upwork/jhinku-tutorials$ psql -U postgres
Password for user postgres:

The default user postgres has a database called postgres, we need to create our database, which we will use to test our if statement query.

postgres=#

Create a new database using the following command:

postgres=# create database if_statement_db;
CREATE DATABASE

To move from the postgres database to if_statement_db, use the command provided below and note that we are connected to the new database as user postgres.

postgres=# \c if_statement_db;
You are now connected to database "if_statement_db" as user "postgres".
if_statement_db=#

Create a table called phone with the fields id, phone_name, phone_color, and phone_price. Define a query using the data provided below.

if_statement_db=# create table phone(
if_statement_db(# id SERIAL UNIQUE NOT NULL,
if_statement_db(# phone_name varchar(50),
if_statement_db(# phone_type varchar(50),
if_statement_db(# phone_price integer,
if_statement_db(# PRIMARY KEY(id));
CREATE TABLE

Insert some records in the phone table. These records will help us to perform the conditional if statement query.

if_statement_db=# insert into phone(phone_name, phone_type, phone_price)
if_statement_db-# values('Sumsung A7', 'Refurbished',600);
INSERT 0 1
if_statement_db=# insert into phone(phone_name, phone_type, phone_price)
if_statement_db=# values('Motorola', 'new',800);
INSERT 0 1
if_statement_db=# insert into phone(phone_name, phone_type, phone_price)
if_statement_db=# values('Iphone 10', 'new',700);
INSERT 0 1

Create a file on your machine and name it data.sql or anything you like. Write the if statement query to be executed against the phone table in this file.

Example (data.sql):

DO
$do$
BEGIN
    IF EXISTS(SELECT * FROM phone) THEN
        DELETE FROM phone;
    ELSE
        INSERT into phone(phone_name, phone_type, phone_price)
        VALUES('Sumsung A7', 'Refurbished',600);

        INSERT into phone(phone_name, phone_type, phone_price)
        VALUES('Motorola', 'new',800);

        INSERT into phone(phone_name, phone_type, phone_price)
        VALUES('Iphone 10', 'new',700);
    END IF;
END
$do$

Our query will check if any records exist in the table. If records exist, those records will be deleted from the table.

If the table does not have any records, then the query inserts a new record.

Execute the data.sql file using the following command. Since our table contains some values, we should expect the delete operation to be performed as the if condition will evaluate to true.

if_statement_db=# \i /home/david/Documents/work/upwork/jhinku-tutorials/data.sql;
DO

A query that retrieves all values ​​in the database returns zero records.

if_statement_db=# select * from phone;

Output:

 id | phone_name | phone_type | phone_price
----+------------+------------+-------------
(0 rows)

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Killing a process ID in PostgreSQL

Publish Date:2025/04/27 Views:191 Category:PostgreSQL

Today, we will learn how to kill or stop a running query in the background when working with PostgreSQL database. This may happen if the frontend stops working but a background process is still running. In this case, you may want to kill th

How to install and deploy PostgreSQL as a Docker container

Publish Date:2025/04/27 Views:50 Category:PostgreSQL

PostgreSQL , also known as Postgres, is a leading object-relational database system. It is popular because it is highly compliant with the SQL standard and includes additional features that simplify processing complex data sets at scale. Po

Add unique constraint after creating table in PostgreSQL

Publish Date:2025/04/27 Views:63 Category:PostgreSQL

Today we will learn how to add constraints after the rows in a table have been created UNIQUE . The UNIQUE constraint guarantees that the data in a row is unique in that column. So if the column ID exists, all rows will have unique values,

Creating a Schema in PostgreSQL

Publish Date:2025/04/27 Views:196 Category:PostgreSQL

This article will discuss creating schemas in PostgreSQL using SQL queries or psql. CREATE SCHEMA Use the statement to create a pattern in SQL query To create a new schema, execute the following command. CREATE SCHEMA test_schema To view al

Changing User Password in Postgres

Publish Date:2025/04/27 Views:108 Category:PostgreSQL

In this article, we will change the user password in Postgres. Changing User Passwords in Postgres Using Windows Open from the menu or search bar SQL Shell (psql) . Connect to the default database using the default port. If you set it up wi

Changing column types in Postgres

Publish Date:2025/04/27 Views:91 Category:PostgreSQL

This article shows how to change a column type to another data type in Postgres. ALTER TABLE To change the column type in Postgres, use the command ALTER TABLE table_name ALTER COLUMN column_name [ SET DATA ] TYPE new_type ; Use 表名 , , 列

Importing SQL files in PostgreSQL

Publish Date:2025/04/27 Views:129 Category:PostgreSQL

This article discusses how to import SQL files in PostgreSQL. psql Import SQL files in PostgreSQL using command To import the SQL file, run the following command: psql - U dbuser - h localhost databasename filename. sql If the file is locat

Create a table if it does not exist in PostgreSQL

Publish Date:2025/04/27 Views:197 Category:PostgreSQL

PostgreSQL is an object-relational database system, which means it can support more complex data types than its competitor MySQL. Apart from the above differences, when writing queries for PostgreSQL and MySQL or other database systems, the

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial