A materialized view in MariaDB is an ordinary table that stores the results of a SELECT statement and is refreshed manually or on a schedule.
MariaDB has no MATERIALIZED VIEW keyword, but you can simulate one by copying query results into a physical table. The table holds pre-computed data, letting dashboards and APIs read quickly.
Use materialized views for heavy joins or aggregations on Orders and OrderItems that run repeatedly. Pre-computing totals eliminates expensive scans during business hours.
Create the target table with CREATE TABLE … AS SELECT
. Include only the columns you need and add sensible indexes for look-ups.
CREATE TABLE order_revenue_mv AS
SELECT
o.id AS order_id,
DATE(o.order_date) AS order_day,
SUM(oi.quantity * p.price) AS revenue
FROM Orders o
JOIN OrderItems oi ON oi.order_id = o.id
JOIN Products p ON p.id = oi.product_id
GROUP BY o.id, order_day;
ALTER TABLE order_revenue_mv
ADD PRIMARY KEY (order_id),
ADD INDEX (order_day);
Refresh by truncating then reinserting, or use an atomic swap. The Event Scheduler or external cron keeps the view current.
TRUNCATE TABLE order_revenue_mv;
INSERT INTO order_revenue_mv
SELECT … -- same SELECT as above
SET GLOBAL event_scheduler = ON;
CREATE EVENT refresh_order_revenue_mv
ON SCHEDULE EVERY 1 HOUR
DO
BEGIN
TRUNCATE TABLE order_revenue_mv;
INSERT INTO order_revenue_mv
SELECT … ;
END;
Add indexes that match your SELECT patterns. Keep each view focused on a single reporting need. Use atomic swaps (RENAME TABLE
) to avoid read downtime.
Because it is a table, use DROP TABLE order_revenue_mv;
and remove any associated events or triggers.
Avoid manual updates. The next refresh overwrites changes, creating data drift.
Insert into a staging table, then run RENAME TABLE staging TO order_revenue_mv, order_revenue_mv TO old
. Renaming is atomic.
The scheduler itself is lightweight. Heavy refresh queries should run during off-peak hours or on replicas.