Welcome back to CodeYourCraft! Today, we're diving into the fascinating world of SQL Materialized Views. Let's get started! 📝
Materialized Views are pre-computed, pre-aggregated, or pre-joined database objects that store the results of an SQL query. They allow us to improve performance by providing quick access to frequently used queries without having to recompute the results each time.
Let's create a simple Materialized View. We'll create a table for employees and calculate the total salary for each department.
CREATE MATERIALIZED VIEW dept_salaries AS
SELECT department, SUM(salary) AS total_salary
FROM employees
GROUP BY department;Here's what's happening:
CREATE MATERIALIZED VIEW: This statement creates a new Materialized View.dept_salaries: This is the name of our Materialized View.AS: This keyword is used to give a name to the result of the query.Materialized Views can be updated manually or automatically. To update the dept_salaries Materialized View manually, use the following command:
REFRESH MATERIALIZED VIEW dept_salaries;You can also set up automatic refreshes for your Materialized Views.
To query a Materialized View, simply use the name of the Materialized View in your SQL statement. Here's an example:
SELECT * FROM dept_salaries;This will return the total salary for each department.
SQL supports three types of Materialized Views:
What is a Materialized View in SQL?
That's it for today! In the next lesson, we'll dive deeper into Updatable and Indexed Materialized Views. Stay tuned! 💡