Home > Database > Mysql Tutorial > How to Create Virtual Tables in PostgreSQL using `setof record`?

How to Create Virtual Tables in PostgreSQL using `setof record`?

Mary-Kate Olsen
Release: 2024-12-24 21:18:35
Original
173 people have browsed it

How to Create Virtual Tables in PostgreSQL using `setof record`?

Creating Virtual Tables with setof record in PostgreSQL

This article delves into creating virtual tables using the setof record approach in PostgreSQL. A virtual table does not have its own underlying data storage; instead, it is a temporary data representation based on passed parameters or calculations.

To create a virtual table that returns three columns and an unknown number of rows, utilize the following PL/pgSQL function:

CREATE OR REPLACE FUNCTION f_foo()
  RETURNS TABLE (a int, b int, c int) AS
$func$
BEGIN
RETURN QUERY VALUES
  (1,2,3)
, (3,4,5)
, (3,4,5)
;
END
$func$  LANGUAGE plpgsql IMMUTABLE ROWS 3;
Copy after login

This function uses the RETURNS TABLE clause to define the row type returned by the function. The RETURN QUERY command generates multiple rows using a VALUES expression. The IMMUTABLE and ROWS 3 clauses optimize the function for performance.

To invoke the virtual table, simply call the function:

SELECT * FROM f_foo();
Copy after login

Additionally, you can construct virtual tables using a plain SQL statement:

VALUES (1,2,3), (3,4,5), (3,4,5)
Copy after login

For more complex cases, define column names and types:

SELECT *
FROM  (
   VALUES (1::int, 2::int, 3::int)
        , (3, 4, 5)
        , (3, 4, 5)
   ) AS t(a, b, c);
Copy after login

Finally, encapsulate the virtual table creation into a SQL function:

CREATE OR REPLACE FUNCTION f_foo()
   RETURNS TABLE (a int, b int, c int) AS
$func$
   VALUES (1, 2, 3)
        , (3, 4, 5)
        , (3, 4, 5);
$func$  LANGUAGE sql IMMUTABLE ROWS 3;
Copy after login

By implementing these approaches, you can effectively create virtual tables in PostgreSQL, enabling flexibility and customization in data processing.

The above is the detailed content of How to Create Virtual Tables in PostgreSQL using `setof record`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template