Views and Functions in PostgreSQL

Views and Functions in PostgreSQL streamline SQL query management, with Views suited for fixed queries and Functions offering flexibility through parameter support.


Views

A View is a virtual table that stores an SQL query. It does not occupy disk space and always returns real-time data based on the stored query. However, Views do not allow the use of parameters, which limits their flexibility.

Example of a View to summarize client data:

CREATE VIEW client_summary AS (

SELECT client.id, client.name, client.contact, client_amount.total

FROM client

JOIN (

SELECT sale.client_id, SUM(sale.amount) AS total 

FROM sale 

GROUP BY sale.client_id

) AS client_amount 

ON client.id = client_amount.client_id

WHERE client.id = 1

);

This View works only for a fixed client ID. In this case, 1.


Functions

Functions provide greater flexibility, accepting parameters and using the PL/pgSQL language. They can return values of different types, such as tables.

Example of a Function that returns client data based on a provided ID:

CREATE FUNCTION client_summary(client_id INT) RETURNS TABLE(id INT, name TEXT, contact TEXT, total DECIMAL(10, 2)) AS $$

DECLARE 

BEGIN

RETURN QUERY

SELECT client.id, client.name, client.contact, client_amount.total

FROM client

JOIN (

SELECT sale.client_id, SUM(sale.amount) AS total

FROM sale

GROUP BY sale.client_id

) AS client_amount

ON client.id = client_amount.client_id

WHERE client.id = $1;

END;

$$ LANGUAGE PLPGSQL;

Query for any client:

SELECT * FROM client_summary(1);


Use Views for fixed queries and Functions for dynamic queries.

Comentários

Postagens mais visitadas deste blog

Integration of PostgreSQL and pgAdmin Containers with Docker Compose

Safely Refactoring Endpoints with Postman Tests