[mysql] Case statement in MySQL

I have a database table called 'tbl_transaction' with the following definition:

id INT(11) Primary Key
action_type ENUM('Expense', 'Income')
action_heading VARCHAR (255)
action_amount FLOAT

I would like to generate two columns: Income Amt and Expense Amt.

Is it possible to populate the columns conditionally, using only a SQL Query, such that the output appears in the correct column, depending on whether it is an Expense item or an Income item?

For example:

ID        Heading         Income Amt       Expense Amt
1         ABC             1000             -
2         XYZ             -                2000

I'm using MySQL as the database. I'm trying to use the CASE statement to accomplish this.

Cheers!

This question is related to mysql sql database case

The answer is


Another thing to keep in mind is there are two different CASEs with MySQL: one like what @cdhowie and others describe here (and documented here: http://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#operator_case) and something which is called a CASE, but has completely different syntax and completely different function, documented here: https://dev.mysql.com/doc/refman/5.0/en/case.html

Invariably, I first use one when I want the other.


Try to use IF(condition, value1, value2)

SELECT ID, HEADING, 
IF(action_type='Income',action_amount,0) as Income,
IF(action_type='Expense',action_amount,0) as Expense

MySQL also has IF():

SELECT 
  id, action_heading, 
      IF(action_type='Income',action_amount,0) income, 
      IF(action_type='Expense', action_amount, 0) expense
FROM tbl_transaction

I hope this would provide you with the right solution:

Syntax:

   CASE  
        WHEN search_condition THEN statement_list  
       [WHEN search_condition THEN statement_list]....
       [ELSE statement_list]  
   END CASE

Implementation:

select id, action_heading,  
   case when
             action_type="Expense" then action_amount  
             else NULL   
             end as Expense_amt,   
    case when  
             action_type ="Income" then action_amount  
             else NULL  
             end as Income_amt  
  from tbl_transaction;

Here I am using CASE statement as it is more flexible than if-then-else. It allows more than one branch. And CASE statement is standard SQL and works in most databases.


This should work:

select 
  id
  ,action_heading
  ,case when action_type='Income' then action_amount else 0 end
  ,case when action_type='Expense' then expense_amount else 0 end
from tbl_transaction

Examples related to mysql

Implement specialization in ER diagram How to post query parameters with Axios? PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' is not supported How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Connection Java-MySql : Public Key Retrieval is not allowed How to grant all privileges to root user in MySQL 8.0 MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to database

Implement specialization in ER diagram phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' cannot be loaded Room - Schema export directory is not provided to the annotation processor so we cannot export the schema SQL Query Where Date = Today Minus 7 Days MySQL Error: : 'Access denied for user 'root'@'localhost' SQL Server date format yyyymmdd How to create a foreign key in phpmyadmin WooCommerce: Finding the products in database TypeError: tuple indices must be integers, not str

Examples related to case

PostgreSQL CASE ... END with multiple conditions SQL Server: use CASE with LIKE SQL Server IIF vs CASE SELECT using 'CASE' in SQL SELECT query with CASE condition and SUM() GROUP BY + CASE statement SQL use CASE statement in WHERE IN clause SQL Server - Case Statement where to place CASE WHEN column IS NULL in this query Regarding Java switch statements - using return and omitting breaks in each case