SQL:SQL Views: Virtual Tables for Reusable Queries
SQL•Views

SQL Views: Virtual Tables for Reusable Queries

Views encapsulate complex joins and aggregations into virtual tables that can be queried like real tables.

Syntax

CREATE VIEW view_name AS SELECT ...;

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
CREATE VIEWStatementCreates named virtual table based on SELECT query.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing SQL locally:

CREATE TABLE products (
    id INTEGER PRIMARY KEY,
    name TEXT,
    price REAL,
    is_active INTEGER
);

INSERT INTO products VALUES
    (1, 'Laptop', 1200.00, 1),
    (2, 'Legacy Cable', 5.00, 0),
    (3, 'Monitor', 300.00, 1);

-- Create reusable view for active catalog items
CREATE VIEW active_catalog AS
SELECT id, name, price
FROM products
WHERE is_active = 1;

-- Query view directly
SELECT * FROM active_catalog WHERE price > 500.00;
Expected Output:
id  name    price 
--  ------  ------
1   Laptop  1200.0

How It Works: Step-by-Step

  • Lines 8-12: Populates products table.
  • Lines 15-18: CREATE VIEW encapsulates active filter.
  • Line 21: Queries active_catalog view just like a real table.

Key Concepts

  • Views do not store data physically; they run the underlying query when accessed.
  • Views provide security by restricting direct column visibility to authorized roles.

Common Mistake: Assuming views improve query performance automatically

Standard views re-run the underlying query each time. Use materialized views or indexes for performance.

❌ Incorrect
// Views simplify SQL, but don't cache data without materialization
✅ Correct
// Use indexes on underlying tables to optimize view performance

Related SQL Tutorials & Compiler

Run and test SQL on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

SQL Online Compiler