Postagens

Mostrando postagens de janeiro, 2025

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 Fun...