Operating System Debian

How to Use MySQL and MariaDB Views on Debian 12

A practical guide to SQL views in MariaDB and MySQL 8 on Debian 12: creating them, updating through them, using them for access control, and their performance limits.

A view is a SELECT statement saved under a name. You query it like a table, but it stores no rows of its own: each time you read from it, the server runs the underlying query against the real tables. Views are useful for hiding a complicated join behind a simple name, for giving an application or a reporting user access to part of a table, and for keeping a stable interface while the tables underneath change.

This guide uses Debian 12, where the packaged database server is MariaDB 10.11. Everything shown also works on MySQL 8.0 and 8.4 if you installed MySQL from its own repository, and on the newer MariaDB in Debian 13; differences are pointed out where they exist. Debian 7, which older tutorials targeted, has been unsupported for years.

Requirements

  • A Debian 12 server and a user with sudo rights.
  • A database server. If you do not have one yet, install MariaDB from the Debian repositories:
sudo apt update
sudo apt install -y mariadb-server
sudo mariadb-secure-installation

On Debian the database root account authenticates through the Unix socket, so you open a root session with sudo and no password:

sudo mariadb

With MySQL from the MySQL APT repository, use sudo mysql or mysql -u root -p instead. The SQL below is the same.

Create a sample database

Run these statements in the database shell. They create two small tables that the rest of the guide builds on.

CREATE DATABASE shop CHARACTER SET utf8mb4;
USE shop;

CREATE TABLE customers (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(190) NOT NULL UNIQUE,
  country CHAR(2) NOT NULL,
  active TINYINT(1) NOT NULL DEFAULT 1
);

CREATE TABLE orders (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  customer_id INT UNSIGNED NOT NULL,
  ordered_at DATE NOT NULL,
  total DECIMAL(10,2) NOT NULL,
  status ENUM('pending','paid','refunded') NOT NULL DEFAULT 'pending',
  FOREIGN KEY (customer_id) REFERENCES customers (id)
);

INSERT INTO customers (name, email, country, active) VALUES
  ('Ana Lopez', 'ana@example.com', 'ES', 1),
  ('Ben Carter', 'ben@example.com', 'US', 1),
  ('Chen Wei', 'chen@example.com', 'SG', 0);

INSERT INTO orders (customer_id, ordered_at, total, status) VALUES
  (1, '2025-01-10', 120.00, 'paid'),
  (1, '2025-02-03', 35.50, 'paid'),
  (2, '2025-02-14', 80.00, 'refunded'),
  (2, '2025-03-01', 210.25, 'paid'),
  (3, '2025-03-09', 15.00, 'pending');

Create and query views

A filtered view

The simplest view restricts rows and columns. This one exposes only active customers and leaves out the active flag itself:

CREATE VIEW active_customers AS
SELECT id, name, email, country
FROM customers
WHERE active = 1;

Query it like a table, including your own WHERE and ORDER BY:

SELECT name, email FROM active_customers WHERE country = 'US';

A view over a join

Views pay off when the query is one you would otherwise repeat. This one totals paid orders per customer:

CREATE VIEW customer_totals AS
SELECT c.id AS customer_id,
       c.name,
       COUNT(o.id) AS paid_orders,
       COALESCE(SUM(o.total), 0) AS paid_total
FROM customers c
LEFT JOIN orders o
       ON o.customer_id = c.id AND o.status = 'paid'
GROUP BY c.id, c.name;
SELECT * FROM customer_totals ORDER BY paid_total DESC;

The result has one row per customer: Ben Carter with one paid order of 210.25, Ana Lopez with two totalling 155.50, and Chen Wei with none. Column names in a view come from the SELECT list, so give expressions an alias, and remember that names must be unique within the view.

List and inspect views

Views share the namespace of tables, so SHOW TABLES lists both. To see only views, their definitions and whether they can be written to:

SHOW FULL TABLES IN shop WHERE Table_type = 'VIEW';
SHOW CREATE VIEW customer_totals\G
SELECT TABLE_NAME, IS_UPDATABLE
FROM information_schema.VIEWS
WHERE TABLE_SCHEMA = 'shop';

The last query reports YES for active_customers and NO for customer_totals. The next section explains why.

Change data through a view

A view is updatable when each of its rows maps to exactly one row of a base table. It stops being updatable if the definition contains aggregate or window functions, DISTINCT, GROUP BY, HAVING, UNION, certain joins and subqueries, or if it is forced to use a temporary table. customer_totals uses GROUP BY, so it is read-only. active_customers is a plain filter, so this works and changes the customers table:

UPDATE active_customers SET country = 'MX' WHERE id = 1;

Inserting through a view has extra conditions: the view must contain every base-table column that has no default value, and its columns must be plain column references rather than expressions.

Keep rows inside the view with WITH CHECK OPTION

Without further rules, an update through a view can change a row so that it no longer matches the view's WHERE clause, and the row silently drops out of the view. WITH CHECK OPTION makes the server reject such changes. Redefine the view to include the active column and add the option:

CREATE OR REPLACE VIEW active_customers AS
SELECT id, name, email, country, active
FROM customers
WHERE active = 1
WITH CHECK OPTION;
UPDATE active_customers SET active = 0 WHERE id = 2;

The update now fails with error 1369, CHECK OPTION failed, because the row would leave the view. When a view is built on other views, WITH CASCADED CHECK OPTION (the default) also enforces the conditions of the underlying views, while WITH LOCAL CHECK OPTION checks only the view being defined.

Use views for access control

Privileges can be granted on a view without granting anything on its tables. That lets a reporting account read totals without seeing e-mail addresses:

CREATE USER 'report'@'localhost' IDENTIFIED BY 'replace-with-a-strong-password';
GRANT SELECT ON shop.customer_totals TO 'report'@'localhost';

Leave the root shell with exit and test as the new user:

mariadb -u report -p shop -e "SELECT * FROM customer_totals; SELECT * FROM customers;"

The first statement returns rows; the second is refused with error 1142 because the account has no rights on the table.

This works because views default to SQL SECURITY DEFINER: the query runs with the privileges of the account that created the view, not those of the caller. If you want the caller's own privileges to apply, create the view with SQL SECURITY INVOKER. One consequence of definer security: if the definer account is later dropped, the view stops working until it is recreated by an existing account.

Modify and remove views

CREATE OR REPLACE VIEW replaces a definition in one step and keeps grants on the view; when the view already exists it behaves like ALTER VIEW. To delete a view, which never touches the underlying data:

DROP VIEW IF EXISTS shop.active_customers;

MariaDB additionally accepts CREATE VIEW IF NOT EXISTS; MySQL does not have that clause.

Limits and performance

  • The definition is frozen when the view is created. A view defined with SELECT * does not pick up columns added to the table later, and dropping a column the view uses makes the view fail. List columns explicitly, and run CHECK TABLE view_name; to find broken views.
  • Views are not cached. Neither MySQL nor MariaDB has materialized views. The underlying query runs every time, so a view is exactly as fast as its SELECT and depends on the same indexes.
  • MERGE versus TEMPTABLE. With the default ALGORITHM = UNDEFINED the server merges the view into the outer query when it can, which lets your WHERE conditions use indexes on the base tables. Views with aggregates, DISTINCT or LIMIT are first written to a temporary table and filtered afterwards, which is slower on large tables. Run EXPLAIN SELECT ... FROM view_name to see which case applies.
  • Restrictions. A view cannot refer to temporary tables or user variables, cannot be created as TEMPORARY, and cannot have triggers. An ORDER BY inside a view is ignored when the outer query has its own.

The full rules are in the MySQL manual's CREATE VIEW page and the MariaDB CREATE VIEW reference.

Frequently asked questions

Does a view take up disk space?

Only its definition is stored. The data stays in the base tables, which is also why a view always shows current data and cannot be indexed on its own.

Are views included in backups?

Logical dumps made with mariadb-dump or mysqldump include view definitions together with their definer account. When you restore on another server, make sure that account exists there, or recreate the views under an account that does.

What can I use instead of a materialized view?

Create an ordinary summary table and refresh it on a schedule, for example with a scheduled event or a cron job that runs REPLACE INTO ... SELECT. You trade freshness for speed, and you can index the summary table.

Can I build a view on top of another view?

Yes. Keep the chain short: each layer is expanded at query time, and one non-mergeable view in the chain forces a temporary table for everything above it.

Share story:

Continue reading other guides on How VPS.