📌 SQL Virtual Columns Tutorial

🧮 SQL Virtual Columns Explained

Virtual columns in SQL are computed columns that do not store data physically, but calculate values based on other columns. They are useful for derived or auto-calculated data like age, tax, bonus, etc.

📌 Syntax (Oracle Style)

CREATE TABLE employees (
  id NUMBER PRIMARY KEY,
  name VARCHAR2(50),
  salary NUMBER(8, 2),
  bonus_percentage NUMBER(3),
  bonus_amount GENERATED ALWAYS AS (salary * bonus_percentage / 100) VIRTUAL
);

Explanation:

  • bonus_amount is a virtual column
  • It automatically calculates: salary × bonus_percentage ÷ 100
  • It’s not stored — just calculated when you query it

📋 Sample Data (Bangladeshi Employees)

id name salary bonus_percentage bonus_amount (Virtual)
1Arif50000105000
2Nasrin6000053000
3Faruk55000126600

🔍 Query the Table

SELECT name, salary, bonus_percentage, bonus_amount
FROM employees;

Output will show: calculated bonus amount for each employee — no need to insert it manually.

💡 Use Cases

  • đŸŽ¯ Automatically calculate age from birthdate
  • 💰 Calculate tax or discount values
  • 📊 Create dynamic fields like full name (first + last)

⚠️ Notes

  • ❌ You cannot insert or update data in a virtual column directly
  • ✅ Virtual columns can be used in indexes
  • đŸšĢ Not all databases support `VIRTUAL` keyword — mainly available in Oracle

📝 Bonus: MySQL Generated Column

CREATE TABLE employees (
  id INT PRIMARY KEY,
  name VARCHAR(50),
  salary DECIMAL(8,2),
  bonus_percentage INT,
  bonus_amount DECIMAL(8,2) GENERATED ALWAYS AS (salary * bonus_percentage / 100) STORED
);

In MySQL:

  • STORED — stores the result in the table
  • VIRTUAL — calculates on demand (default if not stored)
📌 Summary:
Virtual columns are auto-calculated fields that make your table smarter and reduce manual data entry. They're especially useful in reporting and automation.
sql virtual column example, oracle virtual column syntax, generated column mysql, bonus calculation virtual, dynamic column in sql, bangladesh employee table example, blogger sql tutorial

āĻ•োāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāχ:

āĻāĻ•āϟি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āϟ āĻ•āϰুāύ