Types From Tables in PL/pgSQL
In PL/pgSQL, functions can reuse types of columns in tables.
1create table books (2 id serial primary key,3 title text,4 author text5);6
7create or replace function print_title(id integer)8 returns void9 as $$10declare11 title_to_print books.title%type;12begin13 select title14 into title_to_print15 from books16 where books.id = $1;17
18 raise notice 'Title: %', title_to_print;19end20$$ language plpgsql;21
22insert into books (title, author)23values ('The Great Gatsby', 'F. Scott Fitzgerald');24
25select print_title(1);26-- NOTICE: Title: The Great Gatsby
Similarly, you can hold the entire row in a variable.
1create or replace function print_book(id integer)2 returns void3 as $$4declare5 book_to_print books%rowtype;6begin7 select *8 into book_to_print9 from books10 where books.id = $1;11
12 raise notice 'Book Row: %', book_to_print;13end14$$ language plpgsql;15
16select print_book(1);17-- NOTICE: Book Row: (1,"The Great Gatsby","F. Scott Fitzgerald")
Note that %rowtype
is meant for variable declaration, not for return types.
In a Return Type
If you’d like the return type of a function to be a table’s row type, you can use returns setof table_name
.
1create or replace function get_book(id integer)2 returns setof books3 as $$4begin5 return query6 select *7 from books8 where books.id = $1;9end10$$ language plpgsql;11
12select * from get_book(1);
id | title | author |
---|---|---|
1 | The Great Gatsby | F. Scott Fitzgerald |
The record
type
You can also use type record
, which is a row type with no predefined structure.
1create or replace function print_book_record(id integer)2 returns void3 as $$4declare5 book_to_print record;6begin7 select *8 into book_to_print9 from books10 where books.id = $1;11
12 raise notice 'Book Row: %', book_to_print;13end14$$ language plpgsql;15
16select print_book_record(1);17-- NOTICE: Book Row: (1,"The Great Gatsby","F. Scott Fitzgerald")
Wow! You read the whole thing. People who make it this far sometimes
want to receive emails when I post something new.
I also have an RSS feed.