INTERMEDIATE SQL REVIEWER
1 VIEWS
1️⃣
👉 What is a View?
A view is a virtual table created from an SQL query.
✅ It does not store data—only the query.
✅ It is used to:
- Simplify complex queries
- Restrict access to certain data
Basic Commands for Views:
CREATE VIEW view_name AS
SELECT column1, column2
FROM table_name;
SELECT * FROM view_name;
DROP VIEW view_name;
Types of Views:
Type Description
Simple View From one table only, no GROUP BY or
functions
Complex View From multiple tables, includes GROUP BY
or functions
Inline View A subquery inside FROM clause acting as a
temporary table
✅ Example of Complex View:
CREATE VIEW view_name AS
SELECT column_name, COUNT(col1) AS count_col, SUM(col2) AS sum_col
FROM table_name
GROUP BY column_name;
✅ Example of Inline View:
SELECT column_name, SUM(Total) AS total_sum
FROM (
SELECT column_name, col1 * col2 AS Total
FROM table_name
WHERE condition
) AS TempView
GROUP BY column_name;
2️⃣INTEGRITY CONSTRAINTS
👉 What are Constraints?
Rules to keep data valid and consistent in the database.
Constraint What it Does
Primary Key Makes sure each row is unique and not
NULL
Foreign Key Links one table to another (ensures valid
references)
Unique Makes sure column values are unique (can
allow NULL)
Not Null Makes sure a column cannot be empty
(NULL)
Check Makes sure values follow a condition (e.g.,
price ≥ 0)
Default Gives a default value if no value is provided
Composite Key Primary key made up of multiple columns
✅ Example of Check Constraint:
ALTER TABLE employees
ADD CONSTRAINT chk_age CHECK (age >= 18);
3️⃣SQL SCHEMAS
👉 What is a Schema?
A schema is like a folder in a database that groups related objects (tables, views, indexes,
etc.).
✅ It helps:
- Organize database objects
- Control permissions
- Create a namespace to avoid name conflicts
✨ Key Points to Remember:
✅ A view is like a saved SQL query that acts as a table.
✅ Constraints protect data by setting rules.
✅ A schema keeps database objects organized and secure.