Is it possible to write having clause without group by clause in the query?

Yes. We all aware that GROUP BY and HAVING clauses are used only when we need to work with a group of records. Also most of us are in a misconception that, we can’t write HAVING clause without GROUP BY in the query. But, to be frank it is possible :) Look at the below example to get a clear picture.

—————————————-
USE [master]
GO
—————————————-
— Create table StudentInfo
—————————————-
CREATE TABLE [dbo].[StudentInfo](
[SID] [int] NOT NULL PRIMARY KEY,
[Name] [varchar](100) NULL,
[Marks] [int] NULL)
GO
—————————————-
— Insert 4 records into StudentInfo
—————————————-
INSERT [dbo].[StudentInfo]
([SID], [Name], [Marks])
VALUES (1, ‘AAA’, 100)
GO
INSERT [dbo].[StudentInfo]
([SID], [Name], [Marks])
VALUES (2, ‘BBB’, 200)
GO
INSERT [dbo].[StudentInfo]
([SID], [Name], [Marks])
VALUES (3, ‘CCC’, 300)
GO
INSERT [dbo].[StudentInfo]
([SID], [Name], [Marks])
VALUES (4, ‘DDD’, 100)
GO
—————————————-
— Ex1: Having without Group by
—————————————-
SELECT MAX(SID) AS [SID],
MIN(Marks) AS [Marks]
FROM [dbo].[StudentInfo]
HAVING MIN([SID]) < MAX([SID])
—————————————-
Output:

Having-without-GroupBy
—————————————-
— Ex2: Having without Group by
—————————————-
SELECT MAX(SID) AS [SID],
MIN(Marks) AS [Marks]
FROM [dbo].[StudentInfo]
HAVING MAX([SID]) > 1
—————————————-
Output:

Having-without-GroupBy

Happy Learning :)

Leave a Reply

Your email address will not be published. Required fields are marked *