What is the RETURNING clause in SQL?
A database is a collection of structured data stored in an organized manner. Using SQL, we can perform multiple operations such as creating tables, inserting data into tables, modifying the records, and deleting the existing data from the tables. The basic clauses in SQL are:
SELECT: Retrieve data from tablesFROM: Specify data source tablesWHERE: Filter rows based on conditionsORDER BY: Sort result rowsGROUP BY: Group rows for aggregate functionsJOIN: Combine data from multiple tablesINSERT INTO: Add new rows to a tableUPDATE: Modify existing data in a table
The RETURNING clause in SQL
The RETURNING clause in SQL is used to retrieve values from a data modification statement, such as INSERT, UPDATE, or DELETE after the statement has been executed. This can be particularly useful when we want to know the values that were actually inserted, updated, or deleted as a result of the operation.
<DML Operation>-- Other optional statementsRETURNING <Returned_Column(s)>;
Code explanation
Line 1: The
<DML Operation>represents a Data Manipulation Language (DML) operation, which can be one of the following —INSERT,UPDATE, orDELETE— for theRETURNINGclause. These operations are used to manipulate data in the database.Line 2: The “-- Other optional statements” comment indicates that we can include additional SQL statements before the
RETURNINGclause if needed for any specific use case.Line 3:
RETURNINGis the keyword that is used for theRETURNINGclause. The<Returned_Column(s)>represents the column or columns whose values we want to retrieve, after performing the DML operation. We can specify the column names that we want to return from the affected rows.
Importance of the RETURNING clause
While we can achieve similar results using separate SELECT statements, the RETURNING clause offers several advantages:
Advantages | Explanation |
Reduced Round-trips | When we use the |
Consistency and Atomicity | By using the |
Efficiency | Using a single query with the |
Simplicity and Readability | The |
Optimized Execution | Depending on the database system, using the |
While we can certainly achieve similar results by performing a SELECT statement after a data modification, using the RETURNING clause streamlines the process. Using the RETURNING clause also provides a more efficient and integrated way to retrieve specific data related to the modified rows. It’s a powerful feature that enhances both the performance and the clarity of the SQL code when working with data modifications.
Code example
Let’s look at the sections below, which show a specific example of the RETURNING clause with the INSERT, UPDATE, and DELETE commands.
First of all, we need to set up the database.
Setting up the database
We’ll use a simple database named Employees having four columns, the emp_id, emp_name, dept, and date_of_joining.
--Creating Employees tableCREATE TABLE IF NOT EXISTS Employees (emp_id SERIAL PRIMARY KEY,emp_name TEXT,dept TEXT,date_of_joining DATE);--Inserting data into Employees tableINSERT INTO Employees (emp_name, dept, date_of_joining)VALUES('Usama Khan', 'HR', '2022-01-01'),('Fatima Ahmed', 'Sales', '2022-02-15'),('Hassan Ali', 'IT', '2022-09-20'),('Saira Khan', 'IT', '2022-06-15'),('Ahmad Malik', 'HR', '2022-07-10'),('Bilal Ahmed', 'HR', '2023-01-20'),('Noor Fatima', 'Sales', '2023-02-15'),('Zainab Khan', 'Sales', '2022-08-25'),('Sana Khan', 'HR', '2022-10-15'),('Aamir Malik', 'Sales', '2022-11-30'),('Amna Raza', 'IT', '2022-12-25'),('Ali Hassan', 'IT', '2022-03-10'),('Ayesha Siddiqui', 'HR', '2022-04-05'),('Usman Ahmed', 'Sales', '2022-05-20'),('Imran Malik', 'IT', '2023-03-10');SELECT * FROM Employees;
Code explanation
Lines 1–7: A table named the
Employeesis created with four columns, theemp_id( , primary key),serial SERIAL is a keyword used to create an auto-incrementing integer column. When you define a column as SERIAL, PostgreSQL automatically generates a unique integer value for each new row inserted into the table. This is commonly used for primary key columns to ensure that each row has a unique identifier. emp_name,dept, anddate_of_joining.Lines 9–26: A few records are inserted into the
Employeestable using theINSERT INTOcommand.Line 28: Displays the data using the
SELECTstatement.
The INSERT command
In the following SQL operation, we’ll demonstrate the process of inserting a new employee's information into the Employees table. This query will include the employee’s name, department, and date of joining. Additionally, we’ll utilize the RETURNING clause to retrieve the newly inserted record. Press the “Run” button below to see the output:
INSERT INTO Employees (emp_name, dept, date_of_joining)VALUES ('Ayesha Sultan', 'HR', '2023-08-23')RETURNING *;
Code explanation
Lines 1–2: The query inserts the employee’s name “Ayesha Sultan,” department as “HR,” and the joining date, which is “2023-08-23.”
Line 3: After the insertion, the query retrieves the newly inserted record using the
RETURNINGclause.
The UPDATE command
In the following SQL operation, we’ll demonstrate the process of updating an existing employee’s information in the Employees table. Let’s suppose the date of joining of Ayesha Sultan is accidentally recorded as “2023-08-23,” whereas it should have been correctly noted as “2023-08-12.” We’ll fix the date using the UPDATE command. Additionally, we’ll utilize the RETURNING clause to retrieve the modified record. Press the “Run” button to see the output:
UPDATE EmployeesSET date_of_joining = '2023-08-12'WHERE emp_id=16RETURNING *;
Code explanation
Lines 1–3: The query modifies the employee’s record of “Ayesha Sultan,” whose
emp_idis 16, and sets the date of joining to “2023-08-12.”Line 4: After the modification, the query retrieves the modified record using the
RETURNINGclause.
The DELETE command
In the following SQL operation, we’ll demonstrate the process of deleting an existing employee’s information in the Employees table. Imagine a scenario where “Ayesha Sultan,” a key member of the company, has made the decision to part ways with the company. In accordance with this transition, we’ll utilize the DELETE command to remove her record from the database. Additionally, we’ll utilize the RETURNING clause to retrieve the deleted record. Press the “Run” button to see the output:
DELETE FROM EmployeesWHERE emp_id=16RETURNING *;
Code explanation
Lines 1–2: The query deletes the employee’s record of “Ayesha Sultan,” whose
emp_idis 16.Line 3: After the deletion, the query retrieves the deleted record using the
RETURNINGclause.
Conclusion
Our exploration of the RETURNING clause in SQL has revealed its valuable role in optimizing and streamlining database operations. By seamlessly integrating data modification and retrieval within a single query, the RETURNING clause reduces the need for additional round trips to the database server. This results in enhanced efficiency and performance. This powerful feature also ensures data consistency and enables us to obtain specific values resulting from the INSERT, UPDATE, or DELETE commands, while maintaining code readability. As we conclude our discussion, it’s evident that the RETURNING clause stands as a versatile tool for enhancing the precision and effectiveness of our database interactions.
Free Resources