SQL Tutorial

SQL Introduction SQL Aggregate Functions SQL Aliases SQL And SQL Any All SQL Avg SQL Between SQL Case SQL Comments SQL Count SQL Delete SQL Distinct SQL Exists SQL Groupby SQL Having SQL In SQL Insert_into SQL Is Not Null SQL Join SQL Full Outer Join SQL Inner Join SQL Left Join SQL Right Join SQL Self Join SQL Like SQL Min Max SQL NOT Operator SQL Null SQL Operators SQL OR operator SQL OrderBy SQL Select SQL Select Into SQL Top Limit Fetch SQL Store Procedures SQL Sum SQL Union SQL Update SQL Where SQL Wildcards

SQL Database

SQL Alter Table SQL Auto increment SQL BackupDB SQL Check SQL Constrains SQL Create View SQL CreateDB SQL CreateTable SQL Data types SQL Dates SQL DefaultConstrain SQL DropDB SQL DropTable SQL Foreign Key SQL Hosting SQL Index SQL injections SQL Not NULL SQL PrimaryKey SQL Unique SQL Views

SQL SUM Function Tutorial

Example Table

We will use the following table named sales for our examples:


    CREATE TABLE sales (
        sale_id INT PRIMARY KEY,
        product_name VARCHAR(50),
        quantity INT,
        price DECIMAL(10, 2)
    );

    INSERT INTO sales (sale_id, product_name, quantity, price) VALUES
    (1, 'Laptop', 2, 1200.00),
    (2, 'Mouse', 5, 25.00),
    (3, 'Keyboard', 3, 45.00),
    (4, 'Monitor', 1, 300.00),
    (5, 'Chair', 4, 150.00);
    

Sales Table

sale_id product_name quantity price
1 Laptop 2 1200.00
2 Mouse 5 25.00
3 Keyboard 3 45.00
4 Monitor 1 300.00
5 Chair 4 150.00

Using the SQL SUM Function

The SQL SUM function is used to calculate the total sum of a numeric column. In this tutorial, we will demonstrate how to use the SUM function with the sales table.

Example: Calculating Total Sales Quantity

To calculate the total quantity of all products sold:


    SELECT SUM(quantity) AS total_quantity FROM sales;
    

Result:

Query SELECT SUM(quantity) AS total_quantity FROM sales;
Result 15

Example: Calculating Total Sales Revenue

To calculate the total revenue from all sales:


    SELECT SUM(quantity * price) AS total_revenue FROM sales;
    

Result:

Query SELECT SUM(quantity * price) AS total_revenue FROM sales;
Result 3075.00

Example: Calculating Total Revenue by Product

To calculate the total revenue for each product:


    SELECT product_name, SUM(quantity * price) AS total_revenue
    FROM sales
    GROUP BY product_name;
    

Result:

Query SELECT product_name, SUM(quantity * price) AS total_revenue FROM sales GROUP BY product_name;
Result
  • Laptop: 2400.00
  • Mouse: 125.00
  • Keyboard: 135.00
  • Monitor: 300.00
  • Chair: 600.00