Programming

Use PostgreSQL Views to Give Application Queries a Stable, Reusable Interface

Build a PostgreSQL view over orders and customers, query it through an application-facing interface, and test changes to its published columns with representative SQL.

A change to a database query can ripple through an application when several endpoints, reports, or jobs each contain their own version of the same join. PostgreSQL views let you name a SELECT query and use that name in later queries. That gives application code a reusable place to request a defined set of columns without repeating the join every time.

This tutorial builds an order-reporting view over orders and customers. You will create example tables, define the view, query it with caller-specific filters, and test a change to its output. The goal is a deliberately maintained interface—not a promise that the database will prevent every incompatible change.

The PostgreSQL tutorial demonstrates the core pattern as CREATE VIEW ... AS SELECT ..., followed by a query against the view name. The examples below apply that pattern to an order/customer join.

The problem: repeated query shapes

Suppose a reporting page needs an order identifier, date, customer name, and total. Another endpoint needs the same join, but filters the result for one customer. If both consumers write the join independently, each has to know the underlying table names and join condition.

Start with a small schema. Run this in a disposable database or a development schema where these table names are available:

CREATE TABLE customers (
    id   integer PRIMARY KEY,
    name text NOT NULL
);

CREATE TABLE orders (
    id           integer PRIMARY KEY,
    customer_id  integer NOT NULL REFERENCES customers (id),
    order_date   date NOT NULL,
    order_total  numeric(10, 2) NOT NULL
);

The shared query shape is:

SELECT
    o.id AS order_id,
    o.order_date,
    c.name AS customer_name,
    o.order_total
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id;

The view will give this result a database name. The diagram shows the intended boundary: callers request the view’s columns, while the view definition contains the common join.

flowchart LR
    A["Application query"] --> B["Named view"]
    B --> C["Orders and customers"]

A regular view, as used here, is a named query interface. The tutorial example does not establish a separate stored or refreshed copy of the rows, so this pattern should not be mistaken for a materialized result.

1. Choose the columns that form the interface

Before writing CREATE VIEW, decide what a caller should be able to select. This example publishes four fields:

View column Meaning in this example
order_id The identifier selected from orders.id
order_date The order date
customer_name The name selected from the matching customer
order_total The order total

Use explicit expressions and aliases rather than exposing every source column. That makes the result shape visible in the definition and gives the application consistent names to request.

Consider whether consumers need a customer identifier as well as the display name. Names can be unsuitable as lookup keys in an application because the query then identifies a customer by text rather than by the example’s id. If consumers need to filter by an identifier, include it in the view now or plan a deliberate change before writing callers that depend on the view.

The set of published columns is an interface decision. So are their names and meanings. A caller that selects customer_name depends on that name being present and continuing to mean the customer name. Keep those expectations in mind when reviewing a later edit.

2. Create the view

Run this statement after creating the tables:

CREATE VIEW app_order_summary AS
SELECT
    o.id AS order_id,
    o.order_date,
    c.name AS customer_name,
    o.order_total
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id;

The name app_order_summary describes the result a caller uses. The SELECT after AS defines the columns and joined rows in this example. The PostgreSQL tutorial documents this general form and illustrates selecting from a view by its name.

Keep the first version small enough to review. Here, the view has one join and a four-column projection. If you add a field later, make it clear where the field comes from and which consumers need it. A view that becomes a catch-all for unrelated result shapes can be harder to maintain as an interface.

3. Query the view

Check that the database accepts the definition and that the view can be selected:

SELECT *
FROM app_order_summary;

For application code, prefer listing the columns the query actually uses:

SELECT order_id, order_date, customer_name, order_total
FROM app_order_summary;

The caller now names app_order_summary rather than repeating the join. It still chooses what to retrieve. For example, a report can select a date range and specify its own result order:

SELECT order_id, order_date, customer_name, order_total
FROM app_order_summary
WHERE order_date >= DATE '2025-01-01'
ORDER BY order_date, order_id;

This keeps the shared join in the view and the report-specific date range and ordering in the caller’s query. If a caller requires a particular order, put an ORDER BY in that query so its requirement is explicit.

4. Add a stable key for caller filters

A page for one customer might initially filter by the displayed name:

SELECT order_id, order_date, order_total
FROM app_order_summary
WHERE customer_name = 'Northwind Books'
ORDER BY order_date DESC, order_id DESC;

This works as an example of filtering a view, but filtering on a display name may not suit your application. The example schema already has a customer identifier, so expose that value if callers need to locate a customer by key.

One way to define the view with the key included is:

CREATE OR REPLACE VIEW app_order_summary AS
SELECT
    o.id AS order_id,
    o.order_date,
    c.id AS customer_id,
    c.name AS customer_name,
    o.order_total
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id;

The caller can now filter with the identifier and still select only the fields it needs in its result:

SELECT order_id, order_date, customer_name, order_total
FROM app_order_summary
WHERE customer_id = 42
ORDER BY order_date DESC, order_id DESC;

This is an example of publishing a column for filtering even when the caller does not return that column. Before using CREATE OR REPLACE VIEW to alter a view used by an existing application, test the statement against your database and check the expectations of its consumers. Do not assume that every output change is compatible merely because the new query looks additive.

5. Add representative data and test the caller query

A view definition can be syntactically valid and still fail to represent the result your application expects. Insert a small set of rows that exercises more than one customer and more than one order for one customer:

INSERT INTO customers (id, name) VALUES
    (1, 'Northwind Books'),
    (2, 'Harbor Games');

INSERT INTO orders (id, customer_id, order_date, order_total) VALUES
    (101, 1, DATE '2025-01-10', 32.00),
    (102, 1, DATE '2025-02-03', 18.50),
    (201, 2, DATE '2025-01-22', 41.00);

First inspect the joined result, including the customer key added in the revised definition:

SELECT order_id, order_date, customer_id, customer_name, order_total
FROM app_order_summary
ORDER BY customer_id, order_date, order_id;

Then run a query shaped like a customer-specific application request:

SELECT order_id, order_date, order_total
FROM app_order_summary
WHERE customer_id = 1
ORDER BY order_date DESC, order_id DESC;

Check that the returned rows match the intended customer and that the selected names are available as written. Testing the actual caller-shaped query is more useful than checking only SELECT *: it exercises the names, filter, and ordering that the application depends on.

If the existing tables already contain data, avoid blindly running the sample inserts against them. Use isolated test tables or choose non-conflicting test identifiers in a suitable development environment.

6. Treat output changes as interface changes

Once application code uses app_order_summary, the view name and the columns it selects become assumptions in that code. Before editing the definition, review the change from the caller’s perspective.

A practical checklist:

  1. Write down the current output. Record each column name and what it represents. Note which values are identifiers and which are display fields.
  2. Find consumers. Search application queries, reports, and scheduled jobs for the view name and the columns they select or filter.
  3. Describe the exact change. Adding a column is different from renaming one, changing its meaning, or changing which rows the view returns.
  4. Coordinate the migration and caller changes. Check that a deployed caller will not request a column that is unavailable in the database, or rely on a meaning the view no longer provides.
  5. Run representative queries. Test both the new caller and queries used by existing consumers against the changed schema.

For example, adding customer_id gives the application a useful filter in this tutorial. After making the change, test both the query that uses customer_id and an earlier query that selects only order_id, order_date, and order_total. If you want to rename or remove a published column, treat it as potentially breaking until you have established that no consumer relies on it.

The SQL above illustrates the view definition and querying pattern. The exact migration procedure for an established database depends on the database objects and application deployment process involved; test the change in the environment where it will be applied.

7. Keep the reusable part in the view

Use the view for the query shape that several consumers share. Keep caller-specific decisions in the caller query where possible. In this example, the view owns the order/customer join and the published columns. One caller can select a date range; another can filter on customer_id; each can request its own ordering.

This separation makes a consumer query easier to read:

SELECT order_id, order_date, order_total
FROM app_order_summary
WHERE customer_id = 1
  AND order_date >= DATE '2025-01-01'
ORDER BY order_date DESC, order_id DESC;

A view does not remove the need to understand its definition. When a result surprises a caller, inspect the join and projection in the view as well as the caller’s filters. Keep the view focused enough that its name and columns communicate what result it supplies.

Finish with an application-facing query

The complete example definition, including the customer key used for filtering, is:

CREATE OR REPLACE VIEW app_order_summary AS
SELECT
    o.id AS order_id,
    o.order_date,
    c.id AS customer_id,
    c.name AS customer_name,
    o.order_total
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id;

A consumer can then use the named result without repeating that join:

SELECT order_id, order_date, customer_name, order_total
FROM app_order_summary
WHERE customer_id = 1
ORDER BY order_date DESC, order_id DESC;

The implementation is small, but the interface still needs care. Choose the output columns deliberately, test real caller-shaped queries, and review changes to names or meanings as changes that application consumers may need to accommodate.

External Sources used for this article

Related Articles

View all →

Put it into practice

Related tools

All tools →