Thursday, 10 July 2014

Difference between a Having clause and a Where clause in SQL Server?



Difference between a Having clause and a Where clause?

Having Clause

The HAVING clause used with aggregate functions.
Having Clause Syntax:
 

SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value;

Where Clause
The WHERE clause is used to filter records. The WHERE clause is used to extract only those records that fulfill a specified criterion.

Where Clause Syntax:


SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;

HAVING Clause Vs WHERE Clause


  • Where specify a search condition for a group or an aggregate. But HAVING clause can be used only with the SELECT statement.
  • HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause.

  • Having Clause is basically used only with the GROUP BY function in a query, whereas WHERE Clause is applied to each row before they are part of the GROUP BY function in a query. 

  • Where applies to each and single row, whereas having applies to summarized rows (summarized with GROUP BY) 

  • WHERE clause is used for filtering rows and it applies on each and every row, while HAVING clause is used to filter groups in SQL.

  • One syntax level difference between WHERE and HAVING clause is that, former is used before GROUP BY clause, while later is used after GROUP BY clause.

No comments:

Post a Comment