This article was published as a part of the Data Science Blogathon.
SQL clauses like HAVING and WHERE both serve to filter data based on a set of conditions. The difference between the functionality of HAVING and WHERE as SQL clauses are generally asked for in SQL interview questions. In this article, we will explain the functionalities and differences between the HAVING and WHERE clauses using an example.
SQL HAVING clause fetches the necessary records from the aggregated rows or groups on the basis of the given condition. It is generally used along with the GROUP BY clause and applies to the column operations. It operates on the aggregate functions such as ‘SUM’, ‘COUNT’, ‘MAX’, ‘MIN’, or ‘AVG’. We can use the HAVING clause only with SELECT statements. It cannot be used with UPDATE or DELETE statements. The syntax is as follows:
Syntax of the HAVING Clause with the SELECT statement:
SELECT column_1, column_2, column_3, column_N
FROM Table_Name
WHERE condition
GROUP BY column_1, column_N
HAVING condition
ORDER BY column_1, column_2, column_N;
SQL WHERE clause fetches the necessary records from a single table or multiple tables that meet the given condition. The WHERE clause can function without the GROUP BY clause and can perform row operations. It is used with single row functions like character functions, general functions, case conversion functions, date functions, or number functions. We can use the WHERE clause with any SELECT, UPDATE, and DELETE statement. The syntax is as follows:
a) Syntax of the WHERE Clause with the SELECT statement:
SELECT column_1, column_2, column_3, column_N
FROM Table_Name
WHERE condition;
b) Syntax of WHERE Clause with the UPDATE statement:
UPDATE Table_Name
SET column_1=value_1, column_2=value_2, column_3=value_3, column_N=value_N
WHERE condition;
c) Syntax of WHERE Clause with the DELETE statement:
DELETE FROM Table_Name WHERE condition;
In the following example, we will demonstrate the functionality of the HAVING and WHERE clause:
Let’s start by creating a database called Student:
>> CREATE database Student;
Use the Student database:
>> USE Student;
Let’s create the Student_Score table with Student_ID as the primary key:
>> CREATE TABLE Student_Score(
Student_ID INT NOT NULL PRIMARY KEY,
Student_Name varchar(20),
Gender varchar(20),
Math_Score INT,
Bio_Score INT);
Using the SHOW TABLES statement, you can view the tables in the current database:
Insert the values into the Employee_detail table, then use the SELECT command to view the contents:
>> INSERT INTO Student_Score(Student_ID, Student_Name, Gender, Math_Score, Bio_Score)
VALUES(1001, ‘Tom Ford’, ‘Male’, 68, 90),
(1002, ‘Ananya Verma’, ‘Female’, 97, 86),
(1003, ‘Eva Jackson’, ‘Female’, 86, 72),
(1004, ‘John Smith’, ‘Male’, 65, 91),
(1005, ‘Tanvi Sharma’, ‘Female’, 89, 63),
(1006, ‘Lilly Mathew’, ‘Female’, 74, 82);
>> SELECT * FROM Student_Score;
HAVING clause with SELECT statement:
Our goal is to find out the average Math_Score of students who are gender grouped and have an average Math_Score greater than 60 and arranged in descending order.
>> SELECT Gender, AVG(Math_Score) as avg_math_score
FROM Student_Score
GROUP BY Gender
HAVING AVG(Math_Score)>60
ORDER BY AVG(Math_Score) DESC;
WHERE clause with SELECT statement:
In your example, we would like to know the Student_ID, Student_Name, Gender, and Bio_Score of the students who score more than 80.
>> SELECT Student_ID, Student_Name, Gender, Bio_Score
FROM Student_Score
WHERE Bio_Score > 80;
WHERE clause with an UPDATE statement:
For the student with Student_ID 1004, we want to update the Math_Score column to 65 and the Bio_Score column to 95.
>> UPDATE Student_Score
SET Math_Score=70, Bio_Score=95
WHERE Student_ID=1004;
We can use the SELECT statement to view the updated Student_Score table:
>> SELECT * FROM Student_Score;
WHERE clause with DELETE statement:
We want to delete the records where the Gender of a student is ‘Male’:
>> DELETE FROM Student_Score
WHERE Gender=’Male’;
We can use the SELECT statement to view the filtered record:
>> SELECT * FROM Student_Score;
HAVING | WHERE | ||
1. | HAVING clause enables you to fetch necessary records from the aggregated rows or groups on the basis of the specified condition. |
WHERE clause enables you to fetch necessary records from the table on the basis of the specified condition. | |
2. | HAVING clause should be used along with the GROUP BY clause and is used after the GROUP BY clause. | It is possible for the WHERE clause to function without the GROUP BY clause and with the GROUP BY Clause, it’s been used before the GROUP BY Clause. | |
3. | HAVING Clause applies to the column operations. | WHERE Clause applies to the row operations. | |
4. | Aggregate functions can be used in the HAVING Clause | Aggregate functions cannot be used in the WHERE Clause | |
5. | HAVING Clause is also known as a post-filter since it selects rows after aggregate calculations have been carried out. | WHERE Clause is also known as a Pre-filter as it selects the rows before aggregation calculations are conducted. |
|
6. | HAVING Clause can only be used with ‘SELECT’ statements, but not with ‘UPDATE’ or ‘DELETE’ statements. | WHERE Clause can be used with the ‘SELECT’, ‘UPDATE’, and ‘DELETE’ statements. | |
7. | HAVING clause can be used with multiple row functions, such as ‘SUM’, ‘COUNT’, ‘MAX’, ‘MIN’, or ‘AVG’. |
|
This article summarized how both HAVING and WHERE clauses work, as well as how they differ. We have used the Student_Score table as an example and performed various operations with HAVING and WHERE clauses. Hopefully, this article will help you better understand how HAVING and WHERE clauses work, as well as how to differentiate them. Feel free to comment below if you have any queries or connect with me on LinkedIn.
I hope you liked my article on SQL clauses? Share in the comments below.
The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.
Passionate about solving business problems with data-driven solutions. Skilled in the field of Data Science and Big Data Engineering.
I have worked on various projects, including developing predictive models, analyzing complex data sets, and designing and implementing data architectures and pipelines.
I enjoy exploring new data science and data engineering techniques and keeping up with the latest industry trends.
Pandas Groupby for Data Aggregation
Understanding SQL WHERE Clause
Advanced SQL for Data Science
Use of Aggregate Functions and GroupBy in SQL
Important SQL Functions Every Data Analyst Must...
Myth Busters in SQL – Structured Query La...
Understand The Basics of Data Analysis using SQL
Understanding SQL INTERSECT Operator
5 Easy Ways to Use SQL WITH Clause
A Step-By-Step Guide To SQL Subquery
We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.
Show details
This site uses cookies to ensure that you get the best experience possible. To learn more about how we use cookies, please refer to our Privacy Policy & Cookies Policy.
It is needed for personalizing the website.
Expiry: Session
Type: HTTP
This cookie is used to prevent Cross-site request forgery (often abbreviated as CSRF) attacks of the website
Expiry: Session
Type: HTTPS
Preserves the login/logout state of users across the whole site.
Expiry: Session
Type: HTTPS
Preserves users' states across page requests.
Expiry: Session
Type: HTTPS
Google One-Tap login adds this g_state cookie to set the user status on how they interact with the One-Tap modal.
Expiry: 365 days
Type: HTTP
Used by Microsoft Clarity, to store and track visits across websites.
Expiry: 1 Year
Type: HTTP
Used by Microsoft Clarity, Persists the Clarity User ID and preferences, unique to that site, on the browser. This ensures that behavior in subsequent visits to the same site will be attributed to the same user ID.
Expiry: 1 Year
Type: HTTP
Used by Microsoft Clarity, Connects multiple page views by a user into a single Clarity session recording.
Expiry: 1 Day
Type: HTTP
Collects user data is specifically adapted to the user or device. The user can also be followed outside of the loaded website, creating a picture of the visitor's behavior.
Expiry: 2 Years
Type: HTTP
Use to measure the use of the website for internal analytics
Expiry: 1 Years
Type: HTTP
The cookie is set by embedded Microsoft Clarity scripts. The purpose of this cookie is for heatmap and session recording.
Expiry: 1 Year
Type: HTTP
Collected user data is specifically adapted to the user or device. The user can also be followed outside of the loaded website, creating a picture of the visitor's behavior.
Expiry: 2 Months
Type: HTTP
This cookie is installed by Google Analytics. The cookie is used to store information of how visitors use a website and helps in creating an analytics report of how the website is doing. The data collected includes the number of visitors, the source where they have come from, and the pages visited in an anonymous form.
Expiry: 399 Days
Type: HTTP
Used by Google Analytics, to store and count pageviews.
Expiry: 399 Days
Type: HTTP
Used by Google Analytics to collect data on the number of times a user has visited the website as well as dates for the first and most recent visit.
Expiry: 1 Day
Type: HTTP
Used to send data to Google Analytics about the visitor's device and behavior. Tracks the visitor across devices and marketing channels.
Expiry: Session
Type: PIXEL
cookies ensure that requests within a browsing session are made by the user, and not by other sites.
Expiry: 6 Months
Type: HTTP
use the cookie when customers want to make a referral from their gmail contacts; it helps auth the gmail account.
Expiry: 2 Years
Type: HTTP
This cookie is set by DoubleClick (which is owned by Google) to determine if the website visitor's browser supports cookies.
Expiry: 1 Year
Type: HTTP
this is used to send push notification using webengage.
Expiry: 1 Year
Type: HTTP
used by webenage to track auth of webenagage.
Expiry: Session
Type: HTTP
Linkedin sets this cookie to registers statistical data on users' behavior on the website for internal analytics.
Expiry: 1 Day
Type: HTTP
Use to maintain an anonymous user session by the server.
Expiry: 1 Year
Type: HTTP
Used as part of the LinkedIn Remember Me feature and is set when a user clicks Remember Me on the device to make it easier for him or her to sign in to that device.
Expiry: 1 Year
Type: HTTP
Used to store information about the time a sync with the lms_analytics cookie took place for users in the Designated Countries.
Expiry: 6 Months
Type: HTTP
Used to store information about the time a sync with the AnalyticsSyncHistory cookie took place for users in the Designated Countries.
Expiry: 6 Months
Type: HTTP
Cookie used for Sign-in with Linkedin and/or to allow for the Linkedin follow feature.
Expiry: 6 Months
Type: HTTP
allow for the Linkedin follow feature.
Expiry: 1 Year
Type: HTTP
often used to identify you, including your name, interests, and previous activity.
Expiry: 2 Months
Type: HTTP
Tracks the time that the previous page took to load
Expiry: Session
Type: HTTP
Used to remember a user's language setting to ensure LinkedIn.com displays in the language selected by the user in their settings
Expiry: Session
Type: HTTP
Tracks percent of page viewed
Expiry: Session
Type: HTTP
Indicates the start of a session for Adobe Experience Cloud
Expiry: Session
Type: HTTP
Provides page name value (URL) for use by Adobe Analytics
Expiry: Session
Type: HTTP
Used to retain and fetch time since last visit in Adobe Analytics
Expiry: 6 Months
Type: HTTP
Remembers a user's display preference/theme setting
Expiry: 6 Months
Type: HTTP
Remembers which users have updated their display / theme preferences
Expiry: 6 Months
Type: HTTP
Used by Google Adsense, to store and track conversions.
Expiry: 3 Months
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
These cookies are used for the purpose of targeted advertising.
Expiry: 6 Hours
Type: HTTP
These cookies are used for the purpose of targeted advertising.
Expiry: 1 Month
Type: HTTP
These cookies are used to gather website statistics, and track conversion rates.
Expiry: 1 Month
Type: HTTP
Aggregate analysis of website visitors
Expiry: 6 Months
Type: HTTP
This cookie is set by Facebook to deliver advertisements when they are on Facebook or a digital platform powered by Facebook advertising after visiting this website.
Expiry: 4 Months
Type: HTTP
Contains a unique browser and user ID, used for targeted advertising.
Expiry: 2 Months
Type: HTTP
Used by LinkedIn to track the use of embedded services.
Expiry: 1 Year
Type: HTTP
Used by LinkedIn for tracking the use of embedded services.
Expiry: 1 Day
Type: HTTP
Used by LinkedIn to track the use of embedded services.
Expiry: 6 Months
Type: HTTP
Use these cookies to assign a unique ID when users visit a website.
Expiry: 6 Months
Type: HTTP
These cookies are set by LinkedIn for advertising purposes, including: tracking visitors so that more relevant ads can be presented, allowing users to use the 'Apply with LinkedIn' or the 'Sign-in with LinkedIn' functions, collecting information about how visitors use the site, etc.
Expiry: 6 Months
Type: HTTP
Used to make a probabilistic match of a user's identity outside the Designated Countries
Expiry: 90 Days
Type: HTTP
Used to collect information for analytics purposes.
Expiry: 1 year
Type: HTTP
Used to store session ID for a users session to ensure that clicks from adverts on the Bing search engine are verified for reporting purposes and for personalisation
Expiry: 1 Day
Type: HTTP
Cookie declaration last updated on 24/03/2023 by Analytics Vidhya.
Cookies are small text files that can be used by websites to make a user's experience more efficient. The law states that we can store cookies on your device if they are strictly necessary for the operation of this site. For all other types of cookies, we need your permission. This site uses different types of cookies. Some cookies are placed by third-party services that appear on our pages. Learn more about who we are, how you can contact us, and how we process personal data in our Privacy Policy.
Edit
Resend OTP
Resend OTP in 45s
Explained very well. However I would like to know bit clarity on my points, could you please help? 1. Why where clause fails to filter aggregate functions? 2. Can we use group by clause without Agreegate functions? Regards, Janardhan
I interested to learn the SQL class