MySQL Minus Operator



MySQL Minus Operator

The MySQL - operator is used to subtract one number or expression from another. 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 column or value from which to subtract.
  • column2: The column or value to be subtracted.
  • result: An alias for the resulting value.
  • table_name: The name of the table from which to retrieve the data.

Example MySQL Minus 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,
    deduction DECIMAL(10, 2) NOT NULL
);

This query creates a table named salaries with columns for id, base_salary, and deduction.

MySQL CREATE TABLE

Step 3: Inserting Initial Rows

Insert some initial rows into the table:

INSERT INTO salaries (base_salary, deduction)
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: Subtracting Two Columns

Subtract one column from another and display the result:

SELECT base_salary - deduction AS net_salary
FROM salaries;

This query subtracts the deduction column from the base_salary column and displays the result as net_salary.

MySQL SUBTRACT TWO COLUMNS

Step 5: Subtracting a Constant from a Column

Subtract a constant value from a column:

SELECT base_salary - 5000 AS adjusted_salary
FROM salaries;

This query subtracts a constant value of 5000 from the base_salary column, displaying the result as adjusted_salary.

MySQL SUBTRACT CONSTANT FROM COLUMN

Step 6: Subtracting Multiple Columns

Subtract multiple columns and display the result:

SELECT base_salary - deduction - 1000 AS final_salary
FROM salaries;

This query subtracts the deduction column and a constant value of 1000 from the base_salary column, displaying the result as final_salary.

MySQL SUBTRACT 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.