MySQL - Unary Minus Operator (-)



The Unary Minus operator (-) is a type of Arithmetic Operator supported by MySQL. This operator is just used to change the sign of a value in a database table. In other words, whenever this operator is used, the positive values in a database tables are changed to negative values, and vice versa.

Example

The following query will return -3354, which is the negation of postive number 3354 −

SELECT -3354 as Result;

Output

This will produce the following result −

Result
-3354

Example

This below query will return the output as -5788.687, which is the negation of postive float number 5788.687 −

SELECT -5788.687 as Result;

Output

This will produce the following result −

Result
-5788.687

Example

This query will return 7. The first unary minus negates the negative number (-7), changing it to positive −

SELECT -(-263) as Result;

Output

This will produce the following result −

Result
263

Example

Let us see an example where we change the signs of values in a database table column. First, we create a table named CUSTOMERS using the below query −

CREATE TABLE CUSTOMERS (
   ID INT AUTO_INCREMENT,
   NAME VARCHAR(20) NOT NULL,
   AGE INT NOT NULL,
   ADDRESS CHAR (25),
   SALARY DECIMAL (18, 2),
   PRIMARY KEY (ID)
);

The following query inserts 7 records into the above created table −

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES 
(1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ),
(2, 'Khilan', 25, 'Delhi', 1500.00 ),
(3, 'Kaushik', 23, 'Kota', 2000.00 ),
(4, 'Chaitali', 25, 'Mumbai', 6500.00 ),
(5, 'Hardik', 27, 'Bhopal', 8500.00 ),
(6, 'Komal', 22, 'Hyderabad', 4500.00 ),
(7, 'Muffy', 24, 'Indore', 10000.00 );

Execute the following query fetch all the inserted records in the CUSTOMERS table −

Select * From CUSTOMERS;

Following is the CUSTOMERS table −

ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

Now, using the unary minus (-) operator, let us negate the salaries of every customer −

SELECT ID, NAME, SALARY, -SALARY as 'Negative SALARIES' 
FROM CUSTOMERS;

This will produce the following result −

ID NAME SALARY Negative SALARIES
1 Ramesh 2000.00 -2000.00
2 Khilan 1500.00 -1500.00
3 Kaushik 2000.00 -2000.00
4 Chaitali 6500.00 -6500.00
5 Hardik 8500.00 -8500.00
6 Komal 4500.00 -4500.00
7 Muffy 10000.00 -10000.00
Advertisements