Selecting and dividing numbers in a column and displaying the decimal result in integer with MySQL

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Number int
   -> );
Query OK, 0 rows affected (0.50 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Number) values(10);
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(Number) values(20);
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable(Number) values(30);
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable(Number) values(40);
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+----+--------+
| Id | Number |
+----+--------+
|  1 | 10     |
|  2 | 20     |
|  3 | 30     |
|  4 | 40     |
+----+--------+
4 rows in set (0.00 sec)

Here is the query to select an int and dividing using MySQL −

mysql> select Id,Number,(Number/2) AS DivideBy2 from DemoTable;

Ouptut

This will produce the following output. The division result is in decimal values −

+----+--------+-----------+
| Id | Number | DivideBy2 |
+----+--------+-----------+
|  1 |     10 |    5.0000 |
|  2 |     20 |   10.0000 |
|  3 |     30 |   15.0000 |
|  4 |     40 |   20.0000 |
+----+--------+-----------+
4 rows in set (0.00 sec)

If you do not want decimal value, the use the following query and convert in integer −

mysql> select Id,Number,cast((Number/2) AS UNSIGNED) AS DivideBy2 from DemoTable;

Ouptut

This will produce the following output −

+----+--------+-----------+
| Id | Number | DivideBy2 |
+----+--------+-----------+
|  1 | 10     | 5         |
|  2 | 20     | 10        |
|  3 | 30     | 15        |
|  4 | 40     | 20        |
+----+--------+-----------+
4 rows in set (0.00 sec)
raja
Published on 09-Jul-2019 13:42:06
Advertisements