How do you calculate the total of a column in a SQL table?

The SQL SUM function calculates the total of numeric values in a column. It's a fundamental aggregate function used to summarize data.

Sign up for the latest in SQL knowledge from the Galaxy Team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Description

The SUM function in SQL is a powerful tool for quickly calculating the total of a numeric column in a table. It's a core part of aggregate functions, which are used to perform calculations on groups of rows. Imagine you have a table of sales data. Using SUM, you can easily find the total sales for a specific period or category. This function is crucial for tasks like calculating revenue, total inventory, or any other sum-based analysis. It's important to note that SUM only works on numeric data types like integers, decimals, and floats. Trying to use it on text or date columns will result in an error. The SUM function often works in conjunction with GROUP BY to calculate totals for different categories or groups within your data.

Why SQL Sum is important

The SUM function is essential for summarizing data and gaining insights from your database. It's a fundamental building block for more complex queries and reports, enabling quick calculations of totals, sums, and averages.

Example Usage


-- Sample table
CREATE TABLE customer_data (
    customer_id INT PRIMARY KEY,
    full_address VARCHAR(255)
);

INSERT INTO customer_data (customer_id, full_address) VALUES
(1, '123 Main St, Anytown, CA 91234'),
(2, '456 Oak Ave, Somecity, TX 78765'),
(3, '789 Pine Ln, Anothertown, NY 10001');

-- Splitting the address into city and state
SELECT
    customer_id,
    SUBSTRING(full_address, INSTR(full_address, ', ') + 2, INSTR(full_address, ', ', INSTR(full_address, ', ') + 1) - INSTR(full_address, ', ') - 2) AS city,
    SUBSTRING(full_address, INSTR(full_address, ', ', INSTR(full_address, ', ') + 1) + 2, LENGTH(full_address) - INSTR(full_address, ', ', INSTR(full_address, ', ') + 1) - 1) AS state
FROM customer_data;

Common Mistakes

Want to learn about other SQL terms?