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:
| Parameter | Type | Description |
|---|---|---|
| CREATE VIEW | Statement | Creates named virtual table based on SELECT query. |
Ready-to-Run Code Example
Executable in CompilraRun 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
SQL Common Table Expressions (WITH Clause / CTEs)
Write clean, readable multi-step queries using Common Table Expressions (WITH).
SQL INNER JOIN and LEFT JOIN: Combining Relational Tables
Combine related data across tables using INNER JOIN and LEFT OUTER JOIN with ON keys.
SQL DDL: CREATE TABLE, Constraints (PRIMARY KEY, NOT NULL)
Design schemas using CREATE TABLE with PRIMARY KEY, FOREIGN KEY, NOT NULL, and UNIQUE.
SQL Online Compiler
Open in Compilra IDE
Run and test SQL on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.