In this lesson, you will learn how to perform math directly inside your SELECT statements to transform stored data into meaningful information.
Beyond Storing Data
Up until now, we have focused on retrieving data exactly as it is stored in a table. However, raw data often needs a little "processing" before it becomes useful. SQL allows you to use standard arithmetic operators—such as + (addition), - (subtraction), * (multiplication), and / (division)—directly within your query.
Imagine you have a table called products with the columns price and discount. If you want to see the final price for each item, you don't need to manually calculate it or update your database. You can perform the math on the fly:
SELECT
product_name,
price - discount AS final_price
FROM products;
The Power of Computed Expressions
When you use an expression like price - discount, the database calculates the result for every row as it fetches the data. Note that this does not change the actual data stored in your table; it simply creates a temporary, computed result for your current query.
You can also use these expressions to perform projections or to compare values. For example, if you wanted to see the total inventory value for each item:
SELECT
product_name,
price * quantity_in_stock AS inventory_value
FROM products;
Tips for Success
- Use Aliasing: Because computed columns don't have a name in the original table, always use the
ASkeyword to give your result a descriptive label (likeinventory_value). This makes your output much easier to read. - Order of Operations: SQL follows standard mathematical rules (PEMDAS/BODMAS). Use parentheses
()if you need to force a specific order of calculation (e.g.,(price - discount) * quantity). - Nulls in Math: Remember your lesson on
NULLvalues: any arithmetic operation performed on aNULLwill result inNULL. If thediscountis unknown for a product, thefinal_pricewill also return asNULL.
Key Takeaway: Arithmetic expressions allow you to transform raw data into calculated insights during retrieval without altering the underlying table structure.