SQL Server BasicsWhat is SQL Server database?What is RDBMS?What is Normalization?Why we use Denormalization?What_is_SQL?What is PL/SQL?Difference between SQL and PL/SQLDatabase TableOne to One RelationshipOne to Many RelationshipMany to Many RelationshipMany to One RelationshipString Data TypesNumber Data TypesDate Data TypesOther Data TypesCreate DatabaseDrop DatabaseCreating and Managing Users in SQL ServerCreate TableAlter TableDrop TableConstraints in SQL serverPrimary KeyForeign KeyUnique KeyCandidate KeyComposite KeyDifference between primary key and candidate keyPrimary key and foreign key relationshipSurrogate KeyCascading Referential Integrity ConstraintsSelf Referential Integrity ConstraintsInsert into statementInsert multiple recordsUpdate statementDelete statementTruncate statementDifference between Delete and TruncateAlias in SQL ServerSelect statementSelect DistinctSelect TopSelect IntoNull Functions(ISNULL(),NULLIF(),COALESCE())Sub QueryIdentity ColumnSequence objectDifference between sequence and identity columnSQL Server ClausesWHERE ClauseOrder By ClauseTop N ClauseGroup By ClauseHaving ClauseDifference between Where and HavingSQL Server OperatorsArithmetic OperatorsComparison OperatorsLogical OperatorsBitwise OperatorsAny OperatorsAll OperatorsUnion OperatorsUnion All OperatorsDifference between Union and Union AllIntersect OperatorExcept OperatorDifference between Except and IntersectJoinsInner JoinLeft JoinRight JoinFull JoinSelf JoinCross JoinViewsWhat are views?Create views using SSMSIndexed ViewsComplex ViewsCheck Option in ViewCheck Encryption in ViewSchema Binding Option in ViewRead-only ViewsUpdatable ViewsAdvantages and disadvantages of viewsCreate multiple views on one tableCan we implement index on views?Can we Perform Insert, update, delete operation on views?Stored Procedure and FunctionsWhat are Stored Procedures?Why we use stored procedures?Passing parameters to Stored procedureUser-Defined FunctionsDifference between UDF and Stored procedurePre-Defined Functions@@Indentity and Scope_IndentityNULLIF, ISNULL and COALESCE

SQL - Having Clause

The HAVING clause in SQL is used in combination with the GROUP BY clause to filter the result set based on the results of aggregate functions applied to grouped rows. Essentially, it allows you to specify a condition that must be met by a group in order for that group to be included in the result. The HAVING clause is used to filter group-level data, whereas the WHERE clause filters individual rows.

The basic syntax of the HAVING clause is as follows:


SELECT column1, column2, ..., aggregate_function(column)
FROM table_name
GROUP BY column1, column2, ...
HAVING condition;

In the above syntax, column1, column2, ... represent the columns you want to group by, aggregate_function(column) represents the aggregate function you want to apply to each group, and condition represents the filtering condition that applies to the aggregated values.

For example, let's say you have a table called "Orders" with columns such as "OrderID", "CustomerID", "ProductID" and "Quantity". And this "Orders" table have the following sample data:

Table: Orders
OrderID CustomerID ProductID Quantity
110115
210123
310212
410334
510221
610132
710313
810232
910114

Now, let's say you want to find customers who have ordered a total quantity of products greater than or equal to 10. You can use the HAVING clause in conjunction with the GROUP BY clause to achieve this. Here's the SQL query:


SELECT
    CustomerID,
    SUM(Quantity) AS TotalQuantity
FROM
    Orders
GROUP BY
    CustomerID
HAVING
    SUM(Quantity) >= 10;

In this query:

  • We select the "CustomerID" column to identify each customer.
  • We use the SUM function to calculate the total quantity of products ordered by each customer.
  • We give an alias to the calculated column using AS TotalQuantity for clarity.
  • We use the GROUP BY clause to group the rows by "CustomerID," creating one row per customer.
  • We use the HAVING clause to filter the grouped results and include only those customers whose total quantity is greater than or equal to 10.

The result of this query would be:

CustomerID TotalQuantity
10114

In this result, you can see that only customer 101 has a total quantity of products ordered greater than or equal to 10, as per the HAVING clause condition.

The HAVING clause is similar to the WHERE clause, but it operates on the aggregated values of the grouped data rather than individual rows. It allows you to filter the groups based on conditions that cannot be easily expressed using the WHERE clause.

It's important to note that the HAVING clause is applied after the GROUP BY clause, so you can use aggregate functions in the HAVING clause to refer to the result of the aggregation in the SELECT clause.

Additionally, just like the WHERE clause, you can use logical operators such as AND, OR, and NOT in the HAVING clause to create complex conditions.

Remember that the HAVING clause can only be used in combination with the GROUP BY clause. If you're not using the GROUP BY clause in your query, you should use the WHERE clause instead to filter individual rows.