SQL Subtraction Operator

The SQL Subtraction operator is used to subtract one numeric value from another. It is commonly used in SQL queries to compute differences between two columns, perform calculations, and analyze data effectively.

In this tutorial, we will explore how the subtraction operator works in SQL, its syntax, and detailed examples demonstrating its usage.


Syntax of SQL Subtraction Operator

The SQL subtraction operator can be used in two ways:

  • Subtracting two numbers directly: SELECT 50 - 20 AS result;
  • Subtracting values from table columns:
</>
Copy
SELECT column1 - column2 AS result
FROM table_name;

Examples of SQL Subtraction Operator

1. Simple Subtraction Example

We can perform subtraction directly in a SQL query:

</>
Copy
SELECT 100 - 45 AS difference;

Output:

Explanation:

  • The query subtracts 45 from 100, returning 55.
  • This is useful for quick calculations without using a table.

2. Subtracting Values from a Table

Let’s create an employees table to demonstrate the subtraction operator:

</>
Copy
CREATE TABLE employees (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50),
    salary DECIMAL(10,2),
    deductions DECIMAL(10,2)
);

Insert sample records:

</>
Copy
INSERT INTO employees (name, salary, deductions)
VALUES 
('Arjun', 50000, 5000),
('Ram', 45000, 4000),
('John', 60000, 7000),
('Roy', 55000, 6000);

Now, we can calculate the net salary of each employee by subtracting deductions from salary:

</>
Copy
SELECT name, salary, deductions, (salary - deductions) AS net_salary
FROM employees;

Output:

Explanation:

  • salary - deductions calculates the net salary after deductions.
  • The result is displayed in the column net_salary.
  • This is useful for payroll processing, expense tracking, and financial calculations.

Conclusion

In this tutorial for SQL Subtraction Operator (-), we covered:

  1. Basic subtraction between two numbers.
  2. Using the subtraction operator in a SQL query with table data.
  3. Calculating net salary after deductions in an employees table.