Conditionals can be done by means of the CASE operator/expression:

Your query will work with:

SELECT 
    ts, 
    (CASE WHEN column_5 > 0 
     THEN
        0              /* We are ignoring column_1 */
     ELSE
        column_1       /* We are using its value */
     END) + column_2 + column_3 + column_4 AS total
FROM
    t
ORDER BY 
    ts ;

You can check it at http://rextester.com/IHM39024

The CASE expression is standard SQL.

MySQL also offers an IF function that could be used in this case. In fact IF(a,b,c) = CASE WHEN a THEN b ELSE c END.

Answer from joanolo on Stack Exchange
🌐
w3resource
w3resource.com › mysql › aggregate-functions-and-grouping › aggregate-functions-and-grouping-sum().php
MySQL SUM() function
March 2, 2026 - The query will return a single value, which is the sum of the count of rows where 'no_page' is greater than 200 in the 'book_mast' table. This provides insights into the total number of books with more than 200 pages in the dataset. ... mysql> SELECT SUM(mysum) -> FROM( -> SELECT COUNT(*) AS mysum -> FROM book_mast -> WHERE no_page>200) AS bb; +------------+ | SUM(mysum) | +------------+ | 12 | +------------+ 1 row in set (0.02 sec)
🌐
MySQL Tutorial
mysqltutorial.org › home › mysql aggregate functions › mysql sum if
MySQL SUM IF
October 10, 2023 - SELECT SUM( IF( product_name = 'Phone' AND MONTH(sale_date) = 10 AND YEAR(sale_date) = 2023, amount, 0 ) ) AS total_sales FROM sales;Copy
🌐
DataCamp
datacamp.com › doc › mysql › mysql-sum
MySQL SUM() Function: Usage & Examples
It is particularly useful for ... values across a dataset. It calculates the sum of all values in the specified column. sql SELECT SUM(column_name) FROM table_name [WHERE condition];...
🌐
Interview Query
interviewquery.com › p › sum-case-when-sql
SQL Conditional SUM: SUM(CASE WHEN) Syntax, Examples & Best Practices
March 17, 2026 - The pattern is straightforward: use SUM(CASE WHEN … THEN … ELSE 0 END) in grouped queries. This is the canonical MySQL ****SUM(CASE WHEN) approach and works across versions (including 5.7).
🌐
TutorialsPoint
tutorialspoint.com › mysql-sum-query-with-if-condition
MySQL - SUM() Function
July 30, 2019 - If we use the MySQL SUM() function on any column that returns no records (i.e., an empty result set), the SUM() function returns NULL, not zero − · SELECT SUM(SALARY) as TotalSalary FROM CUSTOMERS WHERE NAME = 'Varun'; The above query will return NULL because customer 'Varun' does not exist. In the following query, we are using the DISTINCT keyword with the SUM() function on the "SALARY" column to calculate the sum of unique salary values −
🌐
EDUCBA
educba.com › home › data science › data science tutorials › mysql tutorial › mysql sum()
MySQL sum() | Complete Guide to MySQL sum() with Query Examples
June 6, 2023 - We will take two tables, Products and Suppliers, which: ... SELECT SUM(Unit * CostEach) Product_cost FROM Suppliers INNER JOIN Products ON Supplier_ID WHERE Product_Name = 'Maggie'; ... The result sum value evaluates based on a condition provided ...
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
GeeksforGeeks
geeksforgeeks.org › mysql › conditional-summation
Conditional Summation - GeeksforGeeks
July 23, 2025 - SELECT SUM(quantity_sold) AS ... The Conditional summation in MySQL is a powerful tool for performing the calculations on the subsets of data based on the specific conditions....
Find elsewhere
🌐
W3Schools
w3schools.com › sql › func_mysql_sum.asp
MySQL SUM() Function
String Functions: Asc Chr Concat with & CurDir Format InStr InstrRev LCase Left Len LTrim Mid Replace Right RTrim Space Split Str StrComp StrConv StrReverse Trim UCase Numeric Functions: Abs Atn Avg Cos Count Exp Fix Format Int Max Min Randomize Rnd Round Sgn Sqr Sum Val Date Functions: Date DateAdd DateDiff DatePart DateSerial DateValue Day Format Hour Minute Month MonthName Now Second Time TimeSerial TimeValue Weekday WeekdayName Year Other Functions: CurrentUser Environ IsDate IsNull IsNumeric SQL Quick Ref
🌐
OneUptime
oneuptime.com › home › blog › how to use the sum() function in mysql
How to Use the SUM() Function in MySQL
March 31, 2026 - In MySQL 8.0+, you can compute a running total using the window function version: SELECT order_date, total, SUM(total) OVER (ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS running_total FROM orders WHERE customer_id = 1 ORDER BY order_date; -- Calculate total line value across all order items SELECT order_id, SUM(quantity * unit_price) AS order_subtotal FROM order_items GROUP BY order_id; -- Revenue with discount applied SELECT order_id, SUM(quantity * unit_price * (1 - discount)) AS discounted_total FROM order_items GROUP BY order_id;
🌐
Online Web Tutor
onlinewebtutorblog.com › mysql-sum-with-if-condition-tutorial
MySQL Sum with If Condition Tutorial | Online Web Tutor
January 9, 2022 - If else case block executes mysql queries into a conditional statement. ... Let’s get started. Let’s say we have a table in a database. Table contains data like this – · Inside above image we have a payment_mode column which stores data like Cash, Paypal, Bank Transfer. We want to find the total sum according to payment_method. SELECT SUM(CASE WHEN `payment_mode` = "Cash" THEN amount ELSE 0 END ) AS total_cash, SUM(CASE WHEN `payment_mode` = "Bank Transfer" THEN amount ELSE 0 END ) AS total_bank_transfer, SUM(CASE WHEN `payment_mode` = "Paypal" THEN amount ELSE 0 END) AS total_paypal FROM `finance_reports`
🌐
MySQL Tutorial
mysqltutorial.org › home › mysql aggregate functions › mysql sum() function
MySQL SUM Function
November 10, 2023 - You can use the SUM() function in a SELECT with JOIN clause to calculate the sum of values in a table based on a condition specified by the values in another table.
Top answer
1 of 2
3

Change this:

SUM(btc_total WHERE order_type = 'BUY') AS buy_total

to this:

SUM(IF(order_type='BUY',btc_total,NULL)) AS buy_total

The MySQL IF() function evaluates the first argument as a boolean, if that's TRUE, it returns the second argument, else it returns the third argument.

The IF() will be evaluated for each row, and the return from that expression will get totaled up by the SUM() aggregate.

or, use the more ANSI-standard equivalent to achieve the same result:

SUM(CASE WHEN order_type = 'BUY' THEN btc_total END) AS buy_total

This pattern is commonly referred to as "conditional aggregation".

For the "counts" we can replace COUNT with SUM, like this:

SUM(order_type = 'BUY') AS buy_fill

MySQL evaluates the equality comparison as a boolean, which returns 1, 0 or NULL, which are then totaled up by the SUM aggregate. (A COUNT of that would include zeros and ones, not just the ones.)

The above is equivalent to

SUM( CASE
     WHEN order_type  = 'BUY' THEN 1
     WHEN order_type <> 'BUY' THEN 0
     ELSE NULL
     END
   ) AS buy_fill

If we want to use a COUNT aggregate, we could do it like this:

COUNT(IF(order_type = 'Buy',1,NULL)) AS buy_fill

(We could use any non-null value in place of 1, and get an equivalent result.)

2 of 2
1

"conditional aggregates" conventionally contain a case expression

SELECT
      COUNT(CASE WHEN order_type = 'BUY' THEN order_type END)      AS buy_fill
    , COUNT(CASE WHEN order_type = 'SELL' THEN order_type END)     AS sell_fill
    , SUM(btc_total)                                               AS fill_sum
    , SUM(CASE WHEN order_type = 'BUY' THEN btc_total ELSE 0 END)  AS buy_total
    , SUM(CASE WHEN order_type = 'SELL' THEN btc_total ELSE 0 END) AS sell_total
FROM fill_orders
WHERE coin_id = '$coin'
AND time_stamp >= DATE_SUB(NOW(), INTERVAL 55 SECOND)
🌐
Modern SQL
modern-sql.com › excel › sumif-in-sql
SUMIF in SQL: SUM(CASE WHEN <condition> THEN <value> END)
The Excel function SUMIF can be implemented in SQL Server, Oracle, MySQL, MariaDB and others using a CASE expression.