How to understand differences between ROWTYPE, TYPE, and RECORD in postgresql?
Official documentation explains:https://www.postgresql.org/docs/9.1/plpgsql-declarations.html
- TYPE provides the data type of a variable or table column. You can use this to declare variables that will hold database values. For example, let's say you have a column named user_id in your users table. To declare a variable with the same data type as users.user_id you write: user_id users.user_id%TYPE;.
- ROWTYPE: A variable of a composite type is called a row variable (or row-type variable). Such a variable can hold a whole row of a SELECT or FOR query result, so long as that query's column set matches the declared type of the variable. The individual fields of the row value are accessed using the usual dot notation, for example rowvar.field.
- RECORD: Record variables are similar to row-type variables, but they have no predefined structure. They take on the actual row structure of the row they are assigned during a SELECT or FOR command. The substructure of a record variable can change each time it is assigned to. A consequence of this is that until a record variable is first assigned to, it has no substructure, and any attempt to access a field in it will draw a run-time error.
TYPE CASE
代码语言:javascript复制postgres=# do $$
declare
counter integer := 1;
first_name varchar(50) := 'John';
last_name first_name%type := 'Doe';
payment numeric(11,2) := 20.5;
begin
raise notice '% % % has been paid % USD',
counter,
first_name,
last_name,
payment;
end $$;
NOTICE: 1 John Doe has been paid 20.50 USD
DO
ROWTYPE CASE
代码语言:javascript复制
postgres=# create table actor(actor_id int, fname varchar(20), lname varchar(20));
NOTICE: Table doesn't have 'DISTRIBUTED BY' clause -- Using column named 'actor_id' as the Greenplum Database data distribution key for this table.
HINT: The 'DISTRIBUTED BY' clause determines the distribution of data. Make sure column(s) chosen are the optimal data distribution key to minimize skew.
CREATE TABLE
postgres=# insert into actor values ( 1, 'join', 'mal');
INSERT 0 1
postgres=# select * from actor;
actor_id | fname | lname
---------- ------- -------
1 | join | mal
(1 row)
postgres=# do $$
declare
selected_actor actor%rowtype;
begin
select *
from actor
into selected_actor;
-- show the number of actor
raise notice 'The actor name is % %',
selected_actor.fname,
selected_actor.lname;
end $$;
NOTICE: The actor name is join mal
DO
RECORD TYPE CASE
代码语言:javascript复制postgres=# do $$
declare
r record;
begin
select *
from actor
into r;
-- show the number of actor
raise notice 'The actor name is % %',
r.fname,
r.lname;
end $$;
NOTICE: The actor name is join mal
DO
end~