![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to get the difference between two columns in a new column in MySQL?
Let us first create a table with columns for which we will calculate the difference in a new column −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, LowValue int, HighValue int ); Query OK, 0 rows affected (0.62 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(LowValue,HighValue) values(100,200); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable(LowValue,HighValue) values(300,700); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(LowValue,HighValue) values(1000,2000); Query OK, 1 row affected (0.13 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+----------+-----------+ | Id | LowValue | HighValue | +----+----------+-----------+ | 1 | 100 | 200 | | 2 | 300 | 700 | | 3 | 1000 | 2000 | +----+----------+-----------+ 3 rows in set (0.00 sec)
Here is the query to get the difference between 2 columns −
mysql> select tbl.Id,tbl.LowValue,tbl.HighValue, HighValue-LowValue AS DifferenceBetweenTwoColumns from DemoTable tbl;
This will produce the following output −
+----+----------+-----------+-----------------------------+ | Id | LowValue | HighValue | DifferenceBetweenTwoColumns | +----+----------+-----------+-----------------------------+ | 1 | 100 | 200 | 100 | | 2 | 300 | 700 | 400 | | 3 | 1000 | 2000 | 1000 | +----+----------+-----------+-----------------------------+ 3 rows in set (0.00 sec)
Advertisements