đ§Ž 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) |
---|---|---|---|---|
1 | Arif | 50000 | 10 | 5000 |
2 | Nasrin | 60000 | 5 | 3000 |
3 | Faruk | 55000 | 12 | 6600 |
đ 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 tableVIRTUAL
— 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.
Virtual columns are auto-calculated fields that make your table smarter and reduce manual data entry. They're especially useful in reporting and automation.
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ