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:
- If you're summing numerical values, the result will also be a numerical value.
- If either of the columns contains
NULLvalues, the result will beNULLfor that row unless you handleNULLvalues with functions likeCOALESCE()orIFNULL()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