Thursday, October 8, 2015

SQL - Having Clause

Two reasons of using Having clause
  1. Can't use 'Where' on records filtered by 'Group by'
  2. Aggregate functions can't be used in where clause
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;

Ex.
This will execute
select count(id), max(cast(isactive as varchar(2))) from tb_city
where regionid > 2
group by regionid 

Syntax error
select count(id), max(cast(isactive as varchar(2))) from tb_city
group by regionid 
where regionid > 2

No comments:

Post a Comment

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...