SQL Basics | DML: Data Manipulation Language | HAVING
This section explains how to apply conditions to function values.
For example, suppose you want to retrieve only stores with sales of $1,500 or more. This cannot be done with WHERE alone. In that case, use a command such as HAVING. In general, the HAVING clause appears at the end of an SQL statement. SQL that includes a HAVING clause does not necessarily have to include a GROUP BY clause.
HAVING syntax
The HAVING statement syntax is as follows.
SELECT "column1", SUM("field2")
FROM "table_name"
GROUP BY "field1"
HAVING (function_condition);
Note: The GROUP BY clause is not always required.
HAVING example
store_information table
| store_name | sales | txn_date |
|---|---|---|
| Los Angeles | 1500 | Jan-05-2018 |
| San Diego | 250 | Jan-07-2018 |
| Los Angeles | 300 | Jan-08-2018 |
| Boston | 700 | Jan-08-2018 |
Given the table above, enter the following statement.
SELECT store_name, SUM(sales)
FROM store_Information
GROUP BY store_name
HAVING SUM(sales) > 1500;
The result of the statement above is as follows.
| store_name | SUM(sales) |
|---|---|
| Los Angeles | 1800 |