0
0
SQLquery~5 mins

SELECT with expressions and calculations in SQL

Choose your learning style9 modes available
Introduction
We use SELECT with expressions and calculations to get new information by doing math or combining data right when we ask the database.
You want to find the total price by multiplying quantity and price per item.
You need to calculate someone's age from their birth year stored in the database.
You want to add a discount to a price and see the new price in your results.
You want to combine first and last names into a full name in your query output.
Syntax
SQL
SELECT column1, column2, (expression) AS alias_name FROM table_name;
Expressions can use +, -, *, / for math.
You can rename the result with AS to make it easier to read.
Examples
Calculate total cost by multiplying price and quantity.
SQL
SELECT price, quantity, price * quantity AS total_cost FROM sales;
Combine first and last names into one full name.
SQL
SELECT first_name, last_name, first_name || ' ' || last_name AS full_name FROM employees;
Calculate age by subtracting birth year from current year.
SQL
SELECT birth_year, 2024 - birth_year AS age FROM users;
Sample Program
This creates a products table, adds some items, and calculates total value for each product.
SQL
CREATE TABLE products (product_name TEXT, price DECIMAL, quantity INT);
INSERT INTO products VALUES ('Pen', 1.5, 10), ('Notebook', 3.0, 5), ('Eraser', 0.5, 20);
SELECT product_name, price, quantity, price * quantity AS total_value FROM products;
OutputSuccess
Important Notes
You can use parentheses to control the order of calculations.
Be careful with division by zero; it can cause errors.
Use AS to give clear names to your calculated columns.
Summary
SELECT with expressions lets you do math or combine data when you get results.
Use operators like +, -, *, / inside SELECT to calculate new values.
Rename calculated results with AS for easier reading.