Wednesday, January 1, 2025

How do I sum two columns in SQL?

 To sum two columns in SQL, you can simply use the + operator to add the values of the two columns together within a SELECT statement. Here's an example:

Basic Syntax:

SELECT column1 + column2 AS total_sum
FROM your_table;

Example:

Let's say you have a table called orders with two columns, quantity and price, and you want to get the total amount for each order (i.e., quantity * price):

SELECT quantity + price AS total_sum
FROM orders;

Important Notes:

  1. If you're summing numerical values, the result will also be a numerical value.
  2. If either of the columns contains NULL values, the result will be NULL for that row unless you handle NULL values with functions like COALESCE() or IFNULL() in SQL (depending on your SQL flavor).

For example:

SELECT COALESCE(quantity, 0) + COALESCE(price, 0) AS total_sum
FROM orders;

This will replace any NULL values with 0 before performing the addition.

No comments:

Post a Comment