The RETURNING clause in PostgreSQL is a powerful feature that allows developers to retrieve data directly after executing SQL operations such as INSERT, UPDATE, or DELETE. This feature eliminates the need for multiple queries to fetch modified data, resulting in optimized performance, cleaner code, and more efficient database interactions.
In this article, we will explore how the RETURNING clause works in PostgreSQL with practical examples and outputs. We will also discuss how to implement this clause in real-world scenarios involving auto-incremented primary keys and data validation post-update or deletion, ensuring performance improvements and seamless coding practices.
What is RETURNING in PostgreSQL?
The RETURNING clause lets us instantly get data from a modified record right after an INSERT, UPDATE, or DELETE operations. Instead of running separate queries to retrieve the affected rows, RETURNING helps retrieve the data in the same query. This feature is especially useful for obtaining auto-generated IDs during INSERT, UPDATE and DELETE operations.
Syntax:
1. INSERT Statement with RETURNING
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...)
RETURNING column1, column2, ...;
2. UPDATE Statement with RETURNING
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition
RETURNING column1, column2, ...;
3. DELETE Statement with RETURNING
DELETE FROM table_name
WHERE condition
RETURNING column1, column2, ...;
Examples of RETURNING Clause in PostgreSQL
Example 1: Using RETURNING with INSERT
Let’s consider a scenario where we have a table named employees. We want to insert a new employee named "Alice" into this table and retrieve her newly assigned id right after the insertion. The INSERT operation will generate a new employee ID, which we can retrieve using the RETURNING clause. Here’s how we can accomplish this:
Query:
INSERT INTO employees (name, salary)
VALUES ('Alice', 60000)
RETURNING id, name;
Output
Explanation:
In this example, we inserted Alice into the employees table and received his id immediately. This feature is very useful with auto-incremented primary keys, as it help us to obtain the newly created record's identifier without running an additional query.
Example 2: Using RETURNING with UPDATE
Next, we will see how to use the RETURNING clause with an UPDATE statement. Suppose we need to update Alice's salary to 65,000 and retrieve her id, name, and the updated salary in the same query. This confirms the success of the update and eliminates the need for a second query, thus improving code efficiency.
Query:
UPDATE employees
SET salary = 65000
WHERE name = 'Alice'
RETURNING id, name, salary;
Output
Explanation:
Here, we updated Alice's salary to 65000 and used the RETURNING clause to fetch her id, name, and the new salary in a single operation. This not only confirms the success of the update but also increases our code's efficiency by reducing the number of database calls.
Example 3: Using RETURNING with DELETE
Let's say Alice decides to leave the company, and we need to delete her record from the employees table. We want to confirm which record was deleted by retrieving her id and name after the deletion.
Query:
DELETE FROM employees
WHERE name = 'Alice'
RETURNING id, name;
Output
Explanation:
In this example, we deleted Alice's record from the employees table and received her id and name as output. This way, we can confirm which record was deleted and work with that data if needed.
Why Use the RETURNING Clause?
The RETURNING clause in PostgreSQL offers several advantages:
- Reduces Multiple Queries: Instead of executing separate queries to retrieve updated or inserted data, RETURNING fetches the required information in the same operation.
- Optimizes Performance: By minimizing the number of database calls, this clause helps improve application performance.
- Simplifies Code: Code becomes cleaner and more readable since you don’t need extra logic to fetch modified records.
- Works with Auto-increment Keys: It is especially useful when auto-generated IDs are needed immediately after an INSERT operation.
Conclusion
The RETURNING clause in PostgreSQL is a very useful tool that simplifies data retrieval immediately after INSERT, UPDATE, or DELETE operations. By integrating this feature into our SQL statements, we can efficiently manage our processes, minimize the need for additional queries, and increase overall performance.
By using RETURNING with auto-incremented primary keys, we can instantly capture new record IDs. Additionally, the ability to validate updates and deletions in real-time ensures data accuracy and reliability. Incorporating this feature into your PostgreSQL operations will undoubtedly make your applications more efficient, faster, and easier to maintain.
Similar Reads
PostgreSQL - Function Returning A Table In PostgreSQL, the ability to create functions that return tables enhances the power and flexibility of our database operations. These PostgreSQL RETURN TABLE functions allow us to execute complex queries and return structured data efficiently. In this article, we will explain the PostgreSQL functio
4 min read
PostgreSQL String Functions PostgreSQL is a powerful, open-source relational database management system that offers a rich set of functions and operators for working with string data. String manipulation is an essential task in many applications, and PostgreSQL provides a variety of built-in functions to make working with text
8 min read
PostgreSQL - STRING_AGG() Function The STRING_AGG() function in PostgreSQL is a powerful aggregate function used to concatenate a list of strings with a specified separator. This function is essential for combining string values from multiple rows into a single string, making data aggregation more efficient and readable. Let us get a
2 min read
PostgreSQL Tutorial In this PostgreSQL tutorial youâll learn the basic data types(Boolean, char, text, time, int etc.), Querying and Filtering techniques like select, where, in, order by, etc. managing and modifying the tables in PostgreSQL. Weâll cover all the basic to advance concepts of PostgreSQL in this tutorial.
8 min read
PostgreSQL - Select Into In PostgreSQL, the select into statement to select data from the database and assign it to a variable. Syntax: select select_list into variable_name from table_expression; In this syntax, one can place the variable after the into keyword. The select into statement will assign the data returned by th
2 min read
PostgreSQL - SELECT INTO The PostgreSQL SELECT INTO statement allows users to create a new table directly from the result set of a query. This command is ideal for duplicating or organizing data from an existing table into a new one for further analysis. SELECT INTO does not return data to the client but saves it in a new t
4 min read
PostgreSQL - RIGHT Function The PostgreSQL RIGHT() function, allows you to extract a specified number of characters from the right side of a string. This function can be incredibly useful for various text-processing tasks.Let us get a better understanding of the RIGHT Function in PostgreSQL from this article.SyntaxRIGHT(string
2 min read
Rust and PostgreSQL In today's world of software development, choosing the right programming language and database can significantly impact the performance and reliability of your applications. Rust is a modern programming language that prioritizes safety and performance, while PostgreSQL is a powerful and flexible rel
8 min read
PostgreSQL REVERSE() Function The REVERSE() function in PostgreSQL is a simple yet powerful tool used to reverse the order of characters in a given string. It takes one input which is a string and returns the characters in reverse order. This function is helpful when you need to transform data, run tests or validate information.
4 min read
PostgreSQL List Users In PostgreSQL, managing users and their permissions is important for maintaining database security and organization. As a database administrator or developer, it's essential to understand how to list users and their roles within the PostgreSQL database system. Here user is an entity that can connect
4 min read