MySQL Addition Operator



MySQL Addition Operator

The MySQL + operator is used to add two or more numbers or expressions. This operator is essential for performing arithmetic calculations in SQL queries.


Syntax

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.

Example MySQL Addition Operator

Let's look at some examples of the MySQL + operator:

Step 1: Using the Database

USE mydatabase;

This query sets the context to the database named mydatabase.

MySQL USE DATABASE

Step 2: Creating a Table

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.

MySQL CREATE TABLE

Step 3: Inserting Initial Rows

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.

MySQL INSERT INTO TABLE

Step 4: Adding Two Columns

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.

MySQL ADD TWO COLUMNS

Step 5: Adding a Column and a Constant

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.

MySQL ADD COLUMN AND CONSTANT

Step 6: Adding Multiple Columns

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.

MySQL ADD MULTIPLE COLUMNS

Conclusion

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.