Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT return type?

I realize "an INSERT command returns a command tag," but what's the return type of a command tag?

I.e., what should be the return type of a query language (SQL) function that ends with an INSERT?

For example:

CREATE FUNCTION messages_new(integer, integer, text) RETURNS ??? AS $$
    INSERT INTO messages (from, to, body) VALUES ($1, $2, $3);
$$ LANGUAGE SQL;

Sure, I can just specify the function's return type as integer and either add RETURNING 1 to the INSERT or SELECT 1; after the INSERT. But, I'd prefer to keep things as simple as possible.

like image 341
ma11hew28 Avatar asked Mar 20 '23 05:03

ma11hew28


1 Answers

If the inserted values are of any interest, as when they are processed before inserting, you can return a row of type messages:

CREATE FUNCTION messages_new(integer, integer, text) 
RETURNS messages AS $$
    INSERT INTO messages (from, to, body) VALUES ($1, $2, $3)
    returning *;
$$ LANGUAGE SQL;

And get it like this

select *
from messages_new(1,1,'text');
like image 149
Clodoaldo Neto Avatar answered Apr 02 '23 17:04

Clodoaldo Neto