SQL Server - Subtract (-) Operator
The SQL Server (Transact-SQL) - (subtract) operator is used to subtract two values. It operates on numerical values.
The example below describes how to use subtract operator in various conditions:
Example:
Consider a database table called Sample with the following records:
Data | Var1 | Var2 |
---|---|---|
Data1 | 10 | 1 |
Data2 | 15 | 2 |
Data3 | 20 | 3 |
Data4 | 25 | 4 |
Data5 | 30 | 5 |
Data6 | 35 | 6 |
-
Using with WHERE Clause: To select records of table where difference of Var1 and Var2 column values is greater than 20, the query is given below.
SELECT * FROM Sample WHERE Var1 - Var2 > 20;
The query will produce following result:
Data Var1 Var2 Data4 25 4 Data5 30 5 Data6 35 6 -
Using with AS Clause: The difference of Var1 and Var2 column values can be displayed in a different column using AS clause:
SELECT *, (Var1 - Var2) AS Diff FROM Sample;
The query will produce following result:
Data Var1 Var2 Diff Data1 10 1 9 Data2 15 2 13 Data3 20 3 17 Data4 25 4 21 Data5 30 5 25 Data6 35 6 29 -
Using with UPDATE Clause: To update the column Var1 with the difference of columns Var1 and Var2, the query is given below:
UPDATE Sample SET Var1 = Var1 - Var2; --See result SELECT * FROM Sample;
The query will produce following result:
Data Var1 Var2 Data1 9 1 Data2 13 2 Data3 17 3 Data4 21 4 Data5 25 5 Data6 29 6 -
Using with values: To subtract two values, we can simply use SELECT statement:
SELECT 50 - 30;
The query will produce following result:
20 (1 row(s) affected)
❮ SQL Server Operators