Now, let’s move to the next topic:
Views (Virtual Tables)
🧠 1. What is a VIEW?
A VIEW is a virtual table based on a SQL query
👉 It does NOT store data
👉 It stores the query
Think like this 👇
👉 “Saved SQL query → reuse anytime”
⚡ 2. Why Use Views?
- Simplify complex queries
- Reuse logic
- Hide sensitive data
- Improve readability
⚡ 3. Create a VIEW
CREATE VIEW high_salary_emp AS
SELECT name, salary
FROM employees
WHERE salary > 50000;
🔍 4. Use a VIEW
SELECT FROM high_salary_emp;
✔ Works like a normal table
🔄 5. Update a VIEW
CREATE OR REPLACE VIEW high_salary_emp AS
SELECT name, salary, department
FROM employees
WHERE salary > 50000;
❌ 6. Drop a VIEW
DROP VIEW high_salary_emp;
🎯 7. Real Example
👉 Create view for department-wise average salary
CREATE VIEW dept_avg_salary AS
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department;
👉 Use it:
SELECT FROM dept_avg_salary;
⚡ 8. Important Points
- View does NOT store data
- Changes in table → reflect in view
- Can be used like a table
🎯 9. Practice Tasks
1. Create view for employees with salary > 40k
2. Create view for IT department employees
3. Create view for avg salary per department
4. Query data using created views
5. Drop a view
🔥 Here are the solutions for VIEW practice tasks
✅ 1. Create view for employees with salary > 40k
CREATE VIEW high_salary_emp AS
SELECT
FROM employees
WHERE salary > 40000;
✅ 2. Create view for IT department employees
CREATE VIEW it_employees AS
SELECT
FROM employees
WHERE department = 'IT';
✅ 3. Create view for avg salary per department
CREATE VIEW dept_avg_salary AS
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department;
✅ 4. Query data using created views
SELECT FROM high_salary_emp;
SELECT FROM it_employees;
SELECT FROM dept_avg_salary;
✅ 5. Drop a view
DROP VIEW high_salary_emp;
⚡ Mini Challenge 🔥
👉 Create a view to show top 3 highest salary employees
⚡ Mini Challenge Solution
CREATE VIEW top_3_salary AS
SELECT
FROM employees
ORDER BY salary DESC
LIMIT 3;
👉 Use the view:
SELECT FROM top_3_salary;
🔥 Pro Tip:
Views are heavily used in:
👉 Dashboards
👉 Reporting systems
👉 Data analytics projects
Because they simplify complex SQL 💯
👉 Table → stores data
👉 View → stores query
Double Tap ❤️ For More
Post #2763
7.52K
- ❤ 17