The use of having in SQL

Source: Internet
Author: User

What is the difference between where and having?

Where is a filter before group by, and having a filter for statistics after group by, the general having is used together with group by, combined with aggregate functions, filtered after statistics.

Example:

Table Student (Id,name)

Requirements: Write SQL to isolate the name field from the student table by repeating more than 3 records, and write SQL to delete these duplicate records

First, repeat more than three records:

Select name from student group by name has count (name) >3

Then delete these duplicate records, leaving only one

SELECT * from student where name in (select name from student group by name has COUNT (*) >3)
and ID not in (the Select min (id) from student group by name has COUNT (*) >3)

Analysis: Name is in duplicate records, but ID is not the minimum ID for these duplicate records

It is easy to resolve the data in full repetition, using the DISTINCT keyword, you can get a result set with no duplicates:
SELECT DISTINCT * from TableName
  

Order of Use: Where.....group By....having.....order by

The use of having in SQL

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.