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 Aggregate Functions Tutorial

Example Table

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


    CREATE TABLE companies (
        id INT PRIMARY KEY,
        name VARCHAR(100),
        address VARCHAR(255),
        zip VARCHAR(10),
        city VARCHAR(100),
        revenue DECIMAL(15, 2)
    );

    INSERT INTO companies (id, name, address, zip, city, revenue) VALUES
    (1, 'Company 1', 'Street A, 123', '12345', 'City A', 100000.00),
    (2, 'Company 2', 'Street B, 456', '98765', 'City B', 200000.00),
    (3, 'Company 3', 'Street C, 789', '56789', 'City C', 150000.00),
    (4, 'Company 4', 'Street D, 234', '67890', 'City D', 250000.00),
    (5, 'Company 5', 'Street E, 567', '78901', 'City E', 300000.00);
    
id name address zip city revenue
1 Company 1 Street A, 123 12345 City A 100000.00
2 Company 2 Street B, 456 98765 City B 200000.00
3 Company 3 Street C, 789 56789 City C 150000.00
4 Company 4 Street D, 234 67890 City D 250000.00
5 Company 5 Street E, 567 78901 City E 300000.00

Using COUNT

The COUNT function returns the number of rows that match a specified condition.

SELECT COUNT(*) AS total_companies FROM companies;

Result:

total_companies 5

Using SUM

The SUM function returns the total sum of a numeric column.

SELECT SUM(revenue) AS total_revenue FROM companies;

Result:

total_revenue 1000000.00

Using AVG

The AVG function returns the average value of a numeric column.

SELECT AVG(revenue) AS average_revenue FROM companies;

Result:

average_revenue 200000.00

Using MIN

The MIN function returns the smallest value of the selected column.

SELECT MIN(revenue) AS minimum_revenue FROM companies;

Result:

minimum_revenue 100000.00

Using MAX

The MAX function returns the largest value of the selected column.

SELECT MAX(revenue) AS maximum_revenue FROM companies;

Result:

maximum_revenue 300000.00