0
0
MySQLquery~5 mins

Why computed values add flexibility in MySQL

Choose your learning style9 modes available
Introduction

Computed values let you create new information from existing data without storing extra details. This makes your data more flexible and easier to update.

When you want to show a total price by multiplying quantity and unit price.
When you need to calculate age from a birthdate stored in the database.
When you want to display a full name by combining first and last names.
When you want to find the discount amount based on a percentage and original price.
When you want to convert stored data, like changing temperature from Celsius to Fahrenheit on the fly.
Syntax
MySQL
SELECT column1, column2, (expression) AS computed_column FROM table_name;
Use parentheses around the expression to clearly define the computed value.
The AS keyword gives a name to the computed column for easy reference.
Examples
This calculates total cost by multiplying price and quantity for each row.
MySQL
SELECT price, quantity, (price * quantity) AS total_cost FROM sales;
This combines first and last names into one full name column.
MySQL
SELECT first_name, last_name, CONCAT(first_name, ' ', last_name) AS full_name FROM users;
This computes age by subtracting birth year from the current year.
MySQL
SELECT birthdate, YEAR(CURDATE()) - YEAR(birthdate) AS age FROM people;
Sample Program

This example creates a products table, adds two items, and calculates the total value for each product by multiplying price and quantity.

MySQL
CREATE TABLE products (id INT, name VARCHAR(20), price DECIMAL(5,2), quantity INT);
INSERT INTO products VALUES (1, 'Pen', 1.50, 10), (2, 'Notebook', 3.00, 5);
SELECT name, price, quantity, (price * quantity) AS total_value FROM products;
OutputSuccess
Important Notes

Computed columns do not store data physically; they calculate values when you run the query.

Using computed values helps keep your database smaller and avoids data duplication.

Be careful with complex computations as they can slow down your queries.

Summary

Computed values create new data from existing columns without extra storage.

They help show useful information like totals, ages, or combined names easily.

Using them makes your data flexible and your queries more powerful.