The MySQL +
operator is used to add two or more numbers or expressions. This operator is essential for performing arithmetic calculations in SQL queries.
SELECT column1 + column2 AS result
FROM table_name;
The +
operator has the following components:
column1
: The first column or value to be added.column2
: The second column or value to be added.result
: An alias for the resulting value.table_name
: The name of the table from which to retrieve the data.Let's look at some examples of the MySQL +
operator:
USE mydatabase;
This query sets the context to the database named mydatabase
.
Create a table to work with:
CREATE TABLE salaries (
id INT AUTO_INCREMENT PRIMARY KEY,
base_salary DECIMAL(10, 2) NOT NULL,
bonus DECIMAL(10, 2) NOT NULL
);
This query creates a table named salaries
with columns for id
, base_salary
, and bonus
.
Insert some initial rows into the table:
INSERT INTO salaries (base_salary, bonus)
VALUES (50000.00, 5000.00),
(60000.00, 6000.00),
(55000.00, 5500.00);
This query inserts three rows into the salaries
table.
Add two columns and display the result:
SELECT base_salary + bonus AS total_compensation
FROM salaries;
This query adds the base_salary
and bonus
columns and displays the result as total_compensation
.
Add a column and a constant value:
SELECT base_salary + 5000 AS adjusted_salary
FROM salaries;
This query adds the base_salary
column and a constant value of 5000, displaying the result as adjusted_salary
.
Add multiple columns and display the result:
SELECT base_salary + bonus + 1000 AS total_package
FROM salaries;
This query adds the base_salary
and bonus
columns and a constant value of 1000, displaying the result as total_package
.
The MySQL +
operator is a powerful tool for performing arithmetic calculations in SQL queries. Understanding how to use the +
operator is essential for effective data manipulation and analysis in MySQL.