Welcome, fellow coders! Today, we're diving into the captivating world of SQL, and specifically, the SUM function. This powerful tool is an essential part of your programming toolkit, helping you calculate totals in databases. Let's get started!
In simple terms, the SQL SUM function adds up all the values in a column to give you the total. It's a fundamental aggregate function in SQL that you'll encounter in various projects and real-world scenarios.
SELECT SUM(column_name) FROM table_name;Here's what the above SQL statement means:
SELECT: This keyword is used to select data from a database.SUM(): The aggregate function we're focusing on today.column_name: The specific column you want to add up.FROM: This keyword specifies the table or view from which you want to select data.table_name: The name of the table you're working with.Let's imagine we have a simple table called sales with columns id, product, price, and quantity.
CREATE TABLE sales (
id INT PRIMARY KEY,
product VARCHAR(255),
price DECIMAL(10, 2),
quantity INT
);Now, let's insert some data:
INSERT INTO sales (id, product, price, quantity)
VALUES (1, 'Laptop', 1000.00, 5),
(2, 'Mouse', 20.00, 10),
(3, 'Keyboard', 50.00, 20);Now, to find the total sales, we can use the SUM function:
SELECT SUM(price * quantity) FROM sales;This query multiplies the price by quantity for each row in the sales table, and then adds them all up! The output would be:
6200.00
That's the total sales for our three items!
The SUM function can also be combined with the GROUP BY clause to calculate subtotals for specific groups.
SELECT product, SUM(price * quantity) AS total_sales
FROM sales
GROUP BY product;This query groups the sales by product and calculates the total sales for each product. The output would look like this:
product | total_sales
--------|------------
Laptop | 5000.00
Mouse | 200.00
Keyboard| 1000.00
What does the SQL SUM function do?
How would you calculate the total sales for all products in the sales table?
Stay tuned for more SQL lessons! In the next tutorial, we'll explore the AVG function and how it helps you calculate averages in your databases. Happy coding! 🚀