w3resource

Pre-Sort Order Data with a Materialized View


Create a Materialized View with Sorting

Write a PostgreSQL query to create a materialized view that returns orders sorted by order date.

Solution:

-- Create a materialized view that lists orders in descending order of order_date.
CREATE MATERIALIZED VIEW SortedOrders AS
SELECT order_id, order_date, customer_id
FROM Orders
ORDER BY order_date DESC;

Explanation:

  • Purpose of the Query:
    • The goal is to pre-store a sorted list of orders to speed up queries that require ordered data.
    • This demonstrates using ORDER BY within a materialized view definition.
  • Key Components:
    • ORDER BY order_date DESC : Ensures that the orders are sorted by the most recent first.
  • Real-World Application:
    • Beneficial for applications where users frequently view the latest orders, such as order management systems.

Notes:

  • Sorting is performed at refresh time; subsequent queries against the view benefit from the pre-sorted data.

For more Practice: Solve these Related Problems:

  • Write a PostgreSQL query to create a materialized view that sorts customer records by registration date in ascending order.
  • Write a PostgreSQL query to create a materialized view that orders products by price in descending order from the Products table.
  • Write a PostgreSQL query to create a materialized view that sorts event logs by timestamp from the Logs table, displaying the latest first.
  • Write a PostgreSQL query to create a materialized view that orders employee records alphabetically by last name from the Employees table.


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous PostgreSQL Exercise: Create a Materialized View with Filtering.
Next PostgreSQL Exercise: Create a Materialized View for a Reporting Dashboard.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.