
- 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
Set an alternative of WHERE clause for each SELECT field in MySQL
You can use CASE statement −
mysql> create table DemoTable1988 ( Value1 int, Value2 int, Price int ); Query OK, 0 rows affected (0.64 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1988 values(10,7,500); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable1988 values(7,9,400); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1988 values(8,7,200); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable1988 values(7,4,300); Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1988;
This will produce the following output −
+--------+--------+-------+ | Value1 | Value2 | Price | +--------+--------+-------+ | 10 | 7 | 500 | | 7 | 9 | 400 | | 8 | 7 | 200 | | 7 | 4 | 300 | +--------+--------+-------+ 4 rows in set (0.00 sec)
Here is the query to WHERE clause for each SELECT field:
mysql> select sum( case when Value2=7 then Price else 0 end)- sum( case when Value1=7 then Price else 0 end) as Result from DemoTable1988;
This will produce the following output −
+--------+ | Result | +--------+ | 0 | +--------+ 1 row in set (0.23 sec)
- Related Questions & Answers
- Conditional WHERE clause in MySQL stored procedure to set a custom value for NULL values
- Get current year in MySQL WHERE clause?
- Passing an array to a query using WHERE clause in MySQL?
- How to select from table where conditions are set for id and name in MySQL?
- Get all results using WHERE clause in MySQL?
- Using the entire expression in MySQL WHERE clause?
- Update with multiple values in MySQL WHERE clause
- SELECT WHERE IN null in MySQL?
- How to select data in MySQL where a field has a minimum value?
- Select the maximum for each value in a MySQL table?
- Working with MySQL WHERE.. OR query with multiple OR usage. Is there an alternative?
- Concat a field in MySQL SELECT?
- How to use MySQL VIEW with WHERE clause?
- How Can we use MySQL DISTINCT clause with WHERE and LIMIT clause?
- What is the alternative of BETWEEN clause to fetch values between a range in MySQL?
Advertisements