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 GROUP BY 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 ORDER BY SQL Select SQL Select Into SQL Top Limit Fetch SQL Stored Procedures SQL Sum SQL Union SQL Update SQL Where SQL Wildcards

SQL Database

SQL Alter Table SQL Auto increment SQL Backup Database SQL Check SQL Constraints SQL Create View SQL Create Database SQL Create Table SQL Data types SQL Dates SQL Default Constraint SQL Drop Database SQL Drop Table SQL Foreign Key SQL Hosting SQL Index SQL injections SQL Not NULL SQL PrimaryKey SQL Unique SQL Views

SQL Having

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),
        sale_date DATE,
        amount DECIMAL(10, 2)
    );

    INSERT INTO sales (sale_id, product_name, sale_date, amount) VALUES
    (1, 'Product A', '2023-01-01', 100.00),
    (2, 'Product B', '2023-01-02', 150.00),
    (3, 'Product A', '2023-01-03', 200.00),
    (4, 'Product C', '2023-01-04', 250.00),
    (5, 'Product B', '2023-01-05', 300.00);
    

Sales Table

sale_id product_name sale_date amount
1 Product A 2023-01-01 100.00
2 Product B 2023-01-02 150.00
3 Product A 2023-01-03 200.00
4 Product C 2023-01-04 250.00
5 Product B 2023-01-05 300.00

Using SQL HAVING

The SQL HAVING clause is used to filter records that work on summarized GROUP BY results. It is similar to the WHERE clause but is used for groups rather than individual rows.

Example 1: Total Sales Amount by Product with HAVING

To calculate the total sales amount for each product and filter products with total sales greater than 200, use the following query:


    SELECT product_name, SUM(amount) AS total_amount
    FROM sales
    GROUP BY product_name
    HAVING SUM(amount) > 200;
    

Result:

product_name Product A
total_amount 300.00
Product B
450.00

Example 2: Average Sales Amount by Product with HAVING

To calculate the average sales amount for each product and filter products with an average sales amount greater than 200, use the following query:


    SELECT product_name, AVG(amount) AS average_amount
    FROM sales
    GROUP BY product_name
    HAVING AVG(amount) > 200;
    

Result:

product_name Product B
average_amount 225.00
Product C
250.00