Expressions
MySQL expressions are combinations of values, operators, and functions that evaluate to a single value. They are used in conditions, calculations, and dynamic query construction.
Common Uses of MySQL Expressions
- Arithmetic Expressions: Perform calculations.
- String Expressions: Manipulate text.
- Logical Expressions: Create conditions.
- Date Expressions: Handle date operations.
- Comparison Expressions: Compare values.
Examples
- Arithmetic Expression
SELECT price * quantity AS total FROM orders;
Explanation: Calculates the total price for each order.
- String Expression
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM users;
Explanation: Combines
first_name
andlast_name
into a full name. - Logical Expression
SELECT * FROM orders WHERE amount > 50 AND status = 'Paid';
Explanation: Filters orders with amount greater than 50 and status
Paid
. - Date Expression
SELECT CURDATE() - INTERVAL 30 DAY AS last_month;
Explanation: Calculates the date 30 days ago.
- Comparison Expression
SELECT * FROM employees WHERE salary BETWEEN 3000 AND 5000;
Explanation: Filters employees with salaries between 3000 and 5000.