Web20 University

How to create a MySQL Materialized View

Get up to 65% Off Hosting with FREE SSL & FREE Domains!

* Web 2.0 University is supported by it's audience. If you purchase through links on our site, we may earn an affiliate commision.

What Is a Materialized View?

A materialized view is essentially a precomputed result of a query that is stored physically in the database for example in a table to be retrieved easily. Unlike a standard view, which is simply a saved SQL query that runs whenever you query the view, a materialized view contains a snapshot of data at the moment it was created or last refreshed.

In other words:

  • A regular view fetches data dynamically from the underlying tables each time it is accessed, which can slow down performance for large datasets.
  • A materialized view, on the other hand, stores the query results, allowing for faster data retrieval, especially for complex and time-consuming queries.

Why Are Materialized Views Useful?

Materialized views are highly beneficial in scenarios where data does not need to be real-time but requires quick retrieval, such as:

  1. Performance Optimization: If a query is complex and slow, materialized views can improve performance significantly by precomputing and storing the results, avoiding the need to recompute the query every time.
  2. Reduction of Database Load: In a high-traffic application, frequently running the same expensive query can put a strain on your database. Materialized views reduce the load by serving the data directly from a stored snapshot.
  3. Fast Aggregation and Reporting: For analytical workloads where you often perform calculations like sum, average, or count, materialized views can cache those results, speeding up reporting and dashboard generation.
  4. Improved User Experience: Faster query response times lead to an overall better user experience, especially for large-scale applications or BI tools that regularly query large datasets.

When to Use Materialized Views:

  • Complex queries involving joins, aggregations, or subqueries.
  • Dashboards or reporting tools that require fast access to precomputed data.
  • Data that doesn’t change frequently and can tolerate slight latency in updates.

How to Create a Materialized View in MySQL

While MySQL does not natively support materialized views (as some other databases like PostgreSQL do), you can simulate a materialized view using tables and triggers or scheduled refreshes. Here’s a step-by-step guide to creating a materialized view in MySQL.

Step 1: Create a Table to Store the Materialized View

To mimic a materialized view, we first create a table to hold the precomputed query results.

CREATE TABLE materialized_view_sales AS
SELECT product_id, SUM(sales_amount) AS total_sales
FROM sales
GROUP BY product_id;

In this example, the table materialized_view_sales stores the total sales for each product, and this data will be precomputed and stored in the table.

Step 2: Automate Refreshing the Materialized View

The key difference between a materialized view and a simple table is that a materialized view needs to be refreshed to keep the data up-to-date. You can achieve this in MySQL using triggers, scheduled events, or even scripts running in the background.

Option 1: Using Scheduled Events

MySQL’s EVENT scheduler can be used to refresh the materialized view at regular intervals.

CREATE EVENT refresh_materialized_view_sales
ON SCHEDULE EVERY 1 HOUR
DO
BEGIN
    DELETE FROM materialized_view_sales;
    INSERT INTO materialized_view_sales
    SELECT product_id, SUM(sales_amount) AS total_sales
    FROM sales
    GROUP BY product_id;
END;

This event will refresh the materialized view every hour by first clearing out the old data and then running the original query to insert the updated values.

Option 2: Using Triggers

If you need your materialized view to update in real-time when changes are made to the underlying data, you can use triggers. However, be cautious, as this can have performance impacts on write operations.

CREATE TRIGGER update_materialized_view_sales
AFTER INSERT ON sales
FOR EACH ROW
BEGIN
    INSERT INTO materialized_view_sales (product_id, total_sales)
    VALUES (NEW.product_id, NEW.sales_amount)
    ON DUPLICATE KEY UPDATE total_sales = total_sales + NEW.sales_amount;
END;

This trigger will update the materialized view each time new sales data is inserted into the sales table.

Step 3: Query the Materialized View

Once the materialized view is created and refreshed as needed, querying it is simple and fast.

SELECT * FROM materialized_view_sales WHERE product_id = 101;

The query fetches data from the precomputed materialized view, which is far quicker than executing the original aggregation query on the sales table.

Conclusion

Materialized views are a powerful tool for optimizing query performance, particularly in read-heavy applications or when dealing with complex aggregations. Although MySQL does not offer native support for materialized views, you can implement them using tables, triggers, and scheduled events to simulate their behavior.

By using materialized views, you can significantly reduce query load and improve the performance of your MySQL database, making your application more responsive and efficient.


Further Reading:

With these tips and techniques, you can unlock the potential of materialized views in MySQL, helping you to better manage large datasets and optimize performance.

Get up to 65% Off Hosting with FREE SSL & FREE Domains!