

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Perform multiplication in SELECT depending on column value in MySQL?
You can use CASE statement for this. Let us first create a table −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Value1 int, Value2 int ); Query OK, 0 rows affected (0.76 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Value1,Value2) values(10,5); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable(Value1,Value2) values(20,0); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(Value1,Value2) values(40,10); Query OK, 1 row affected (0.28 sec) mysql> insert into DemoTable(Value1,Value2) values(50,0); Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+--------+--------+ | Id | Value1 | Value2 | +----+--------+--------+ | 1 | 10 | 5 | | 2 | 20 | 0 | | 3 | 40 | 10 | | 4 | 50 | 0 | +----+--------+--------+ 4 rows in set (0.00 sec)
Following is the query to perform multiplication in SELECT depending on column value −
mysql> select Value1,Value2, case when Value2 > 0 then Value1*Value2 else 0 end as Multiplication from DemoTable;
This will produce the following output −
+--------+--------+----------------+ | Value1 | Value2 | Multiplication | +--------+--------+----------------+ | 10 | 5 | 50 | | 20 | 0 | 0 | | 40 | 10 | 400 | | 50 | 0 | 0 | +--------+--------+----------------+ 4 rows in set (0.00 sec)
- Related Questions & Answers
- Perform MySQL UPDATE on the basis of DATE value in another column
- Show column value twice in MySQL Select?
- Perform MySQL SELECT on fields containing null values?
- Select data and set value to boolean based on timestamp column in MySQL
- How to perform element-wise multiplication on tensors in PyTorch?
- MySQL SELECT to sum a column value with previous value
- Perform case insensitive SELECT using MySQL IN()?
- Select a specific value between two column values in MySQL?
- How to select the maximum value of a column in MySQL?
- How to perform SELECT using COUNT in MySQL?
- Select minimum row value from a column with corresponding duplicate column values in MySQL
- Perform MySQL SELECT on dates inserted into the table as VARCHAR values
- Exclude rows based on column value when another duplicate column value is found in MySQL?
- C++ Program to Perform Matrix Multiplication
- How to select distinct value from one MySQL column only?
Advertisements