Let’s start with the basics!
A table is a physical structure in the database that stores data. This can be compared to a spreadsheet with rows and columns.
Key Characteristics:
CREATE TABLE employees (
joined TIMESTAMP,
name VARCHAR(255),
department VARCHAR(255),
salary BIGINT
);
A view is a virtual table. It doesn’t store data itself but presents data from one or more tables via a saved SQL SELECT query.
Key Characteristics: -Does NOT store data; it’s just a saved query. -Can be ‘useful’ for security (e.g., hiding certain columns). -Runs one or more underlying queries when refreshed.
CREATE VIEW high_salary_employees AS
SELECT name, salary
FROM employees
WHERE salary > 100000;
Feature | Table | View |
---|---|---|
Data storage | Stores data physically | Does not store data |
Purpose | Store and manage data | Present data in a specific way |
Query Performance | Generally faster (no re-querying) | Slower (runs underlying query each time) |
Dependencies | Independent | Depends on tables and other views |
Security | Less granular | Present exactly what is needed |
Maintenance | May require indexing, tuning | No physical tuning, but query can be tuned |
Like views, but they store the result of the query physically. Useful when performance matters, but data doesn’t need to be real-time. Must be manually refreshed:
CREATE MATERIALIZED VIEW employee_summary AS
SELECT department, COUNT(*) as num_employees
FROM employees
GROUP BY department;
-- Later, when you want fresh data:
REFRESH MATERIALIZED VIEW employee_summary;
So finally, with so much to chose from, what should we use and when?