How to convert positive value to negative while inserting in MySQL?


Let us first create a table

mysql> create table recordsDemo
   -> (
   -> UserId int,
   -> Value int
   -> );
Query OK, 0 rows affected (0.52 sec)

Now insert some records in the table using insert command.

The query is as follows

mysql> insert into recordsDemo values(1,10);
Query OK, 1 row affected (0.17 sec)
mysql> insert into recordsDemo values(3,598);
Query OK, 1 row affected (0.18 sec)
mysql> insert into recordsDemo values(5,786);
Query OK, 1 row affected (0.25 sec)
mysql> insert into recordsDemo values(7,189);
Query OK, 1 row affected (0.16 sec)
mysql> insert into recordsDemo values(9,345);
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement.

The query is as follows

mysql> select *from recordsDemo;

The following is the output

+--------+-------+
| UserId | Value |
+--------+-------+
| 1      | 10    |
| 3      | 598   |
| 5      | 786   |
| 7      | 189   |
| 9      | 345   |
+--------+-------+
5 rows in set (0.00 sec)

Create a second table. The query to create a second table is as follows

mysql> create table PositiveToNegativeValueDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Money int
   -> );
Query OK, 0 rows affected (0.83 sec)

Here is the query to convert positive value to negative while inserting

mysql> insert into PositiveToNegativeValueDemo(Id,Money)
   -> select UserId,(-1*Value) from recordsDemo;
Query OK, 5 rows affected (0.15 sec)
Records: 5 Duplicates: 0 Warnings: 0

Now check table records from the table using select statement.

The query is as follows

mysql> select *from PositiveToNegativeValueDemo;

The following is the output

+------+-------+
| Id   | Money |
+------+-------+
| 1    | -10   |
| 3    | -598  |
| 5    | -786  |
| 7    | -189  |
| 9    | -345  |
+------+-------+
5 rows in set (0.00 sec)

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements