Skip to main content
Documents
Clauses StatementsKeywordsExpressionsFunctionsIndexesPerformance Optimization

MySQL RETURNING Clauses

The `RETURNING` clause is commonly used in some SQL databases to return values from rows affected by `INSERT`, `UPDATE`, or `DELETE` operations without requiring a separate `SELECT` query. However, as of MySQL 8.0, this feature is not natively supported. This document provides alternative methods for achieving similar functionality in MySQL.

Usage Alternatives

While MySQL does not support the `RETURNING` clause directly, users can employ other methods to achieve comparable results, particularly for capturing auto-generated or modified values immediately after a data manipulation operation.

Capturing Inserted IDs

For capturing newly inserted IDs, MySQL offers the `LAST_INSERT_ID()` function:

sql
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
SELECT LAST_INSERT_ID();

This function returns the last automatically generated value that was inserted into an `AUTO_INCREMENT` column.

Using Triggers or Stored Procedures

For capturing updated or deleted values, consider using triggers or stored procedures. These can be designed to log changes or return values of interest:

Using a Trigger

sql
CREATE TRIGGER before_update_example
BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
    # Example logic to store old and new values
END;

Triggers can be used to perform actions based on data changes, such as storing old and new values in a log table.

Using a Stored Procedure

sql
DELIMITER //
CREATE PROCEDURE update_employee_salary(IN emp_id INT, IN new_salary DECIMAL(10,2))
BEGIN
    DECLARE old_salary DECIMAL(10,2);
    SELECT salary INTO old_salary FROM employees WHERE employee_id = emp_id;
    UPDATE employees SET salary = new_salary WHERE employee_id = emp_id;
    SELECT emp_id, old_salary, new_salary;
END //
DELIMITER ;

Stored procedures can encapsulate logic to perform updates and return both old and new values.

Tips and Best Practices

  • Use existing MySQL features. Leverage `LAST_INSERT_ID()`, triggers, and stored procedures for functionality similar to the `RETURNING` clause.
  • Plan for compatibility. Be aware of the MySQL version you are using, as support for the `RETURNING` clause may be introduced in future versions.
  • Optimize performance. When using triggers or procedures, ensure they are efficient to avoid performance bottlenecks.
  • Consider version compatibility. Regularly check MySQL release notes for any updates regarding support for `RETURNING` or similar features.

SQL Upskilling for Beginners

Gain the SQL skills to interact with and query your data.
Start Learning for Free