w3resource

Insert Data and Return Rows with RETURNING in PostgreSQL and OUTPUT in SQL Server


Using RETURNING in PostgreSQL and OUTPUT in SQL Server

Write a SQL query to insert data and return the inserted rows, using RETURNING in PostgreSQL and OUTPUT in SQL Server.

Solution:

-- PostgreSQL
INSERT INTO Employees (Name, Salary)
VALUES ('John Doe', 60000)
RETURNING EmployeeID, Name, Salary;

-- SQL Server
INSERT INTO Employees (Name, Salary)
OUTPUT INSERTED.EmployeeID, INSERTED.Name, INSERTED.Salary
VALUES ('John Doe', 60000);

Explanation:

  • Purpose of the Query :
    • The goal is to demonstrate how to return inserted rows using platform-specific syntax.
  • Key Components :
    • RETURNING (PostgreSQL): Returns inserted rows directly.
    • OUTPUT (SQL Server): Captures inserted rows using the INSERTED virtual table.
  • Why Compare Insertion Results?:
    • Returning inserted rows simplifies confirmation and further processing.
    • Understanding these differences ensures efficient data handling.
  • Real-World Application :
    • In transactional systems, returning inserted rows supports real-time updates.

Additional Notes:

  • Use RETURNING in PostgreSQL and OUTPUT in SQL Server for compatibility.
  • Test queries on all target platforms to ensure consistent results.
  • Important Considerations:
    • Avoid unnecessary use of these features for performance reasons.

For more Practice: Solve these Related Problems:

  • Write a SQL query to insert product data and return the inserted rows, using RETURNING in PostgreSQL and OUTPUT in SQL Server.
  • Write a SQL query to insert customer data and return the inserted rows, using RETURNING in PostgreSQL and OUTPUT in SQL Server.
  • Write a SQL query to insert order data and return the inserted rows, using RETURNING in PostgreSQL and OUTPUT in SQL Server.
  • Write a SQL query to insert employee data and return the inserted rows, using RETURNING in PostgreSQL and OUTPUT in SQL Server.


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous SQL Exercise:Writing a Query that uses INTERSECT in PostgreSQL and INNER JOIN in MySQL.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.