Open In App

PostgreSQL – BEGIN

Last Updated : 01 Feb, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

PostgreSQL BEGIN command is used to initiate a transaction. A transaction is nothing but a unit of work done in the database, the work can be anything from creating tables to deleting them. BEGIN command should be the first word of a transaction.

Syntax :

BEGIN;
// statements

(or) 

BEGIN TRANSACTION;
// statements

By default, PostgreSQL transactions are auto-commit, but to end the transaction block we need to give either COMMIT or ROLLBACK commands. Statements inside the transaction block execute faster than normally given because the CPU uses special disk computation for defining transactions.

Firstly, we have to create a sample table using the below commands for examples

CREATE TABLE students (
    student_id serial PRIMARY KEY,
    full_name VARCHAR NOT NULL,
    marks INT
);

Now we insert data into our student table as follows:

INSERT INTO students (
    student_id,
    full_name,
    marks
)
VALUES
    (1, 'Rahul Kumar', NULL),
    (2, 'Abishek Nayak', 5),
    (3, 'Chandra Gupta', 6),
    (4, 'Sanju Sharma', 8);

Now that the table is ready we can look into some examples.

Example 1:

The below transaction will add another record in the table.

BEGIN;

 INSERT INTO students (
     student_id,
    full_name,
        marks
        
)

    VALUES(
       5, 'Mehboob Dilse', 10
        )
;
        
COMMIT;

Output:

Example 2:

The below transaction will update the record in the table.

BEGIN;
    UPDATE students
    SET marks = 2
    WHERE 
    student_id = 1 ;
        
COMMIT;

Output:


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments