Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
27 views

SQL Server-2 - Clauses

The document discusses various SQL clauses including the WHERE and ORDER BY clauses. It provides examples of using each clause to filter records based on conditions, sort records in ascending or descending order, and update or delete records using clauses.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

SQL Server-2 - Clauses

The document discusses various SQL clauses including the WHERE and ORDER BY clauses. It provides examples of using each clause to filter records based on conditions, sort records in ascending or descending order, and update or delete records using clauses.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

SQL Server – Clauses

1.Where Clause in SQL Server with Examples

If you want to provide the SQL Query with some additional functionalities such as filtering
the records, sorting the records, fetching the records, and grouping the records then you
need to use the SQL Server Clauses along with the SQL Query. So, in simple words, we
can say that SQL Server clauses are used to provide some additional functionalities.

Types of Clauses in SQL Server:


The SQL Server supports the following clauses
1. Where (Filtering the records in a table)
2. Order by clause (sorting the records in ascending or descending order)
3. Top n clause (Fetching top n records)
4. Group by clause (Grouping a set of rows)
5. Having Clause (Filtering the data like where clause)

Note: In this article, we are going to discuss the Where Clause, the rest of the clauses are
going to discuss in our upcoming articles.

Example to Understand Where Clause in SQL Server:


We are going to use the following Gender, Department, and Employee tables to
understand the WHERE clause in SQL Server with Examples.
Please use the below script to create the Gender, Department, and Employee tables
with the required sample data.

--Create Gender table

CREATE TABLE Gender

ID INT PRIMARY KEY IDENTITY(1,1),

Gender VARCHAR(50)

GO

--Create Department table

CREATE TABLE Department

(
ID INT PRIMARY KEY IDENTITY(1,1),

Name VARCHAR(100)

-- Create Employee table

CREATE TABLE Employee

ID INT PRIMARY KEY IDENTITY(1,1),

Name VARCHAR(100),

EmailID VARCHAR(100),

GenderID INT,

DepartmentID INT,

Salary INT,

Age INT,

CITY VARCHAR(100)

GO

--Add the foreign key for GenderID Column

ALTER TABLE Employee

ADD CONSTRAINT Employee_GenderID_FK FOREIGN KEY (GenderID)

REFERENCES Gender(ID)

GO

--Add foreign key for DepartmentID Column

ALTER TABLE Employee

ADD CONSTRAINT Employee_DepartmentID_FK FOREIGN KEY (DepartmentID)


REFERENCES Department(ID)

GO

--Insert data to Gender table

INSERT INTO Gender VALUES('Male')

INSERT INTO Gender VALUES('Female')

INSERT INTO Gender VALUES('Unknown')

GO

--Insert data to Department table

INSERT INTO Department VALUES('IT')

INSERT INTO Department VALUES('HR')

INSERT INTO Department VALUES('Payroll')

GO

--Insert data into Employee table

INSERT INTO Employee VALUES('PRANAYA','PRANAYA@G.COM',1, 1, 25000,


30,'MUMBAI')

INSERT INTO Employee VALUES('TARUN','TARUN@G.COM',1, 2, 30000,


27,'ODISHA')

INSERT INTO Employee VALUES('PRIYANKA','PRIYANKA@G.COM',2, 3, 27000,


25,'BANGALORE')

INSERT INTO Employee VALUES('PREETY','PREETY@G.COM',2, 3, 35000,


26,'BANGALORE')

INSERT INTO Employee VALUES('RAMESH','RAMESH@G.COM',3,2, 26000,


27,'MUMBAI')

INSERT INTO Employee VALUES('PRAMOD','PRAMOD@G.COM',1, 1, 29000,


28,'ODISHA')
INSERT INTO Employee VALUES('ANURAG','ANURAG@G.COM',1, 3, 27000,
26,'ODISHA')

INSERT INTO Employee VALUES('HINA','HINA@G.COM',2,2, 26000, 30,'MUMBAI')

INSERT INTO Employee VALUES('SAMBIT','HINA@G.COM',1, 1, 30000,


25,'ODISHA')

GO

Understanding the Where Clause in SQL Server:


The SQL Server WHERE clause is not a mandatory clause of SQL DML statements, but if
you want to limit the number of rows to be affected by your DML query or the number of
rows to return from your select statement, then you need to use the Where Clause in SQL
Server. That means this clause is used to extract only those results from a SQL statement
(such as SELECT, INSERT, UPDATE, or DELETE statement) that fulfill a specified
condition.

Syntax: WHERE conditions;

Conditions: The conditions that must be met for records to be affected.

Note: The WHERE clause is not only used with the SELECT statement, but can also be
used with the INSERT, UPDATE, or DELETE DML statements.

Example of Where clause with a Single condition


We will start by looking at how to use the Where clause with only a single condition. In the
below example, we used the WHERE clause to filter the results from the employee table.
The below Select SQL statement will return all the rows from the employee table where the
CITY is ‘MUMBAI’. Because the * is used in the Select Statement which will return all the
columns from the employee table.

SELECT * FROM Employee WHERE CITY = ‘MUMBAI’;

Once you execute the above query, you will get the following output. Please have a look at
the City column and notice that the above query returns the employees whose City is
MUMBAI.
Example of Where Clause Using AND Condition in SQL Server:
Let’s look at how to use the WHERE clause with the AND condition in SQL Server. In the
below example, we use the WHERE clause to define multiple conditions. In this case, the
SELECT statement uses the AND condition to return all the employees from the Employee
table whose GenderID is 1 and the Salary is greater than or equal to 27000.

SELECT * FROM Employee WHERE GenderID = 1 AND Salary >= 27000;

When you execute the above SQL query, you will get the following output. Notice we only
got the employees who satisfied the WHERE condition that is GenderId is 1 and Salary is
greater than or equals to 27000.

Example of Where Clause using OR Condition in SQL Server:


Let’s look at how to use the WHERE clause with the OR condition in SQL Server. The
below example uses the WHERE clause to define multiple conditions, but instead of using
the AND condition, it uses the OR condition. In this case, the SELECT statement will return
all ID, Name, EmailID, and CITY column values from the Employee table where the
GenderID is 1 or the Salary is greater than 29000. That means if any of the condition is
satisfied then also the data is going to return.

SELECT ID, Name, EmailID, CITY FROM Employee WHERE GenderID = 1 OR Salary
>= 29000;

When you execute the above query, you will get the following output. Notice we only got the
employees who satisfied the WHERE condition that is GenderId is 1 or Salary is greater
than or equals to 29000.
Example of Where Clause using both AND & OR Conditions in SQL
Server:
Let’s look at how to use the WHERE clause when we combine both the AND & OR
conditions in a single SQL statement. The below example uses the WHERE clause to
define multiple conditions, but it combines the AND condition and the OR condition. The
below example will return all employees that reside in the state of MUMBAI and whose
GenderID is 1 as well as all employees whose DepartmentID is 3.

SELECT * FROM Employee WHERE (CITY = ‘MUMBAI’ AND GenderID = 1) OR


(DepartmentID = 3);

When you execute the above query, you will get the following output.

How to use the WHERE clause with Update Statement in SQL Server?
Let’s look at how to use the WHERE clause when we are working with the UPDATE SQL
statement. In the below example, we use the Where clause to update all the Employee
Salary to 37000 where the DepartmentID is 3.

UPDATE Employee SET Salary = 37000 WHERE DepartmentID = 3

Once you execute the above query, verify the Employee table by executing the below query
and you will see that the Salary is updated to 37000 for all the Employees belonging to the
DepartmentId 3.

SELECT * FROM Employee WHERE DepartmentId = 3;

Once you execute the above query you will get the following output and notice the salary is
updated to 37000 as expected.

How to use the Where clause with Delete Statement in SQL Server?
Let’s look at how to use the WHERE clause when we are working with the DELETE SQL
statement. In the following example, we use the Where clause to DELETE all the
Employees where the CITY is MUMBAI.
DELETE FROM Employee WHERE CITY = ‘MUMBAI’

Once you execute the above query, verify the Employee table and you will see that all the
Employees belonging to the CITY MUMBAI are deleted.

2. Order By Clause in SQL Server

What is Order By Clause and its need in SQL Server?


The Order By Clause in SQL Server is used for sorting the data either in ascending or
descending order of a query based on a specified column or list of columns. That means if
you want to sort the output or result of a query either in ascending or descending order then
you need to use SQL Server Order by Clause. Following is the syntax to use Order By
Clause.

SELECT expressions FROM tables [WHERE conditions] ORDER BY expression [ASC


| DESC];

Parameters or Arguments used with Order By Clause in SQL Server:


1. Expressions: The columns or calculations that we want to retrieve.
2. Tables: The tables from which we want to retrieve the records. There should be at least
one table specified in the FROM clause.
3. WHERE Conditions: It is optional. The conditions must be met for the records to be
selected by the query.
4. ASC: It is optional. If you want to sort the result set in ascending order of the
expression then you need to use ASC.
5. DESC: It is optional. If you want to sort the result set in descending order
by expression then you need to the DESC keyword.

Points to remember while working with Order By Clause in SQL Server:


By default, the Order By Clause in SQL Server will sort the data in ascending order. If you
want to arrange the data in descending order then you must have to use the DESC
keyword. The Order By Clause can be applied to any data type column in the table. This
clause will arrange the data temporarily but not in the permanent store. The Order By
Clause can only be used in Select Statements.

Example to Understand SQL Server Order By Clause:


We are going to use the following Employee table to understand the Order By Clause in
SQL Server with Examples.
Please use the below SQL script to create and populate the Employee table with
sample data.

-- Create Person table

CREATE TABLE Employee

ID INT PRIMARY KEY IDENTITY(1,1),

Name VARCHAR(100),

EmailID VARCHAR(100),

Gender VARCHAR(100),

Department VARCHAR(100),

Salary INT,

Age INT,

CITY VARCHAR(100)

GO

--Insert some test data into Person table

INSERT INTO Employee VALUES('PRANAYA','PRANAYA@G.COM','Male', 'IT',


25000, 30,'MUMBAI')
INSERT INTO Employee VALUES('TARUN','TARUN@G.COM','Male', 'Payroll', 30000,
27,'ODISHA')

INSERT INTO Employee VALUES('PRIYANKA','PRIYANKA@G.COM','Female', 'IT',


27000, 25,'BANGALORE')

INSERT INTO Employee VALUES('PREETY','PREETY@G.COM','Female', 'HR', 35000,


26,'BANGALORE')

INSERT INTO Employee VALUES('RAMESH','RAMESH@G.COM','Male','IT', 26000,


27,'MUMBAI')

INSERT INTO Employee VALUES('PRAMOD','PRAMOD@G.COM','Male','HR', 29000,


28,'ODISHA')

INSERT INTO Employee VALUES('ANURAG','ANURAG@G.COM','Male', 'Payroll',


27000, 26,'ODISHA')

INSERT INTO Employee VALUES('HINA','HINA@G.COM','Female','HR', 26000,


30,'MUMBAI')

INSERT INTO Employee VALUES('SAMBIT','HINA@G.COM','Male','Payroll', 30000,


25,'ODISHA')

GO

Sorting the records without using ASC/DESC attribute in SQL Server:


The SQL Server ORDER BY clause can be used without specifying the ASC or DESC
value. When this attribute is omitted from the clause, the sort order is defaulted to ASC or
ascending order.
SELECT * FROM Employee ORDER BY Name;

The above SQL Server ORDER BY example would return all records sorted by the Name
field in ascending order and would be equivalent to the following ORDER BY clause
example.
SELECT * FROM Employee ORDER BY Name ASC;

When you execute the above query, you will get the following output. Notice the records are
sorted based on the Name in ascending order.
Sorting in Descending Order using Order By DESC Keyword in SQL
Server:
When we want to sort the result set in descending order then we need to use the DESC
attribute in the ORDER BY clause. The below SQL Server ORDER BY example will return
all records sorted by the Name field in the descending order whose Gender is Male.
SELECT * FROM Employee WHERE Gender = ‘Male’ ORDER BY Name DESC;

When you execute the above query, you will get the following output. Notice, the above
returns only the Male employees and then sort the employees by name in descending
order.

Note: If we are using where clause and order by clause in a single query then first where
clause gets executed and then order by clause is gets executed.

How to Sort the Data in SQL Server by the Relative Position?


We can also use the SQL Server ORDER BY clause to sort by relative position in the result
set, where the first field in the result is set to 1. The next field is 2, and so on. For better
understanding, please have a look at the below example. Here, we specify the relative
position as 1 in the order by clause.

SELECT Name, EmailID, Salary FROM Employee WHERE Salary > 26000 ORDER BY 1
DESC;
The above SQL Server ORDER BY statement would return all the records sorted by the
Name field in the descending order whose Salary is greater than 26000. Since the Name
field is in position 1 in the select clause and would be equivalent to the following ORDER
BY clause example.

SELECT Name, EmailID, Salary FROM Employee WHERE Salary > 26000 ORDER BY
Name DESC;

When you execute the above SQL query, you will get the below output.

How to use both ASC and DESC attributes in a Single Select Statement
in SQL Server?
When sorting the result set using the SQL Server ORDER BY clause, we can also use the
ASC and DESC attributes in a single SELECT statement. In the following query, the Order
By Clause will return all records sorted by the Gender field in descending order, with a
secondary sort by Name field in ascending order whose salary is greater than 25000.

SELECT Name, Gender, EmailID, Salary

FROM Employee

WHERE Salary > 25000

ORDER BY Gender DESC, Name ASC;


When you execute the above query, you will get the below output.
Note: When we have multiple columns in order by clause, the data first gets arranged
based on the first column and if any duplicate values are there in the first column then it will
take the support of the second column for the arrangement or else the second column will
not be used.

Understanding the OFFSET and FETCH options used in the Order By


Clause in SQL Server:

OFFSET Option in SQL Server:


When we are using order by clause in a query if we want to eliminate the number of records
(rows) from the starting record (TOP) then we need to use the OFFSET option along with
the order by clause. For better understanding, please have a look at the below query. Here,
first, it will sort the employees by name in ascending order and then skips the top five
records from the result set and the rest will be returning as output.

SELECT * FROM Employee ORDER by Name ASC OFFSET 5 ROWS

When you execute the above query, you will get the following output. Notice, it will skip the
first 5 records in the result set.

FETCH Option in SQL Server:


By using the FETCH option in SQL Server Order By Clause we can specify the number of
rows to return after the offset clause is processed. For better understanding please have a
look at the below query. Here, we are using OFFSET 3 ROWS FETCH NEXT 4 ROWS. It
means once the data is sorted then skip 3 records from the top and then fetch 4 records
only as part of the result set
.
SELECT * FROM Employee ORDER by ID ASC OFFSET 3 ROWS FETCH NEXT 4
ROWS ONLY

Once you execute the above query, you will get the rows from 4 to 7 in the result set
skipping the first 3 rows as shown in the below image.
Example: OFFSET With 0

When we specify OFFSET as 0 means it will skip 0 records. For better understanding,
please have a look at the below query. Here we specified OFFSET as 0 and FETCH as 5.
Means skip 0 records and fetch 5 records.

SELECT * FROM Employee ORDER by ID ASC OFFSET 0 ROWS FETCH NEXT 5


ROWS ONLY

When you will execute the above query, you will get the first 5 records of the result set as
shown in the below image.

Example: FETCH With 0


We can never specify the FETCH value as 0. Because Fetch 0 means it will return 0
records which do not make any sense. For better understanding, please have a look at the
below example. Here, we specify the FETCH as 0.

SELECT * FROM Employee ORDER by ID ASC OFFSET 5 ROWS FETCH NEXT 0


ROWS ONLY

When you execute the above query, it will give the error as The number of rows provided
for a FETCH clause must be greater then zero.

3. Top n Clause in SQL Server

What are Top n Clause and its use in SQL Server?

The Top n Clause in SQL Server is used to specify the number of data rows to return. In
large tables with thousands or millions of data rows, it takes more time to return all the
records, which cause database performance issue. To fix this problem, we can return the
specified number of data rows from a table using Top n Clause in SQL Server. The
following is the syntax to use the TOP N CLAUSE in the SQL server.
SELECT TOP (top_value) [PERCENT] [WITH TIES]

Expressions

FROM Tables

[WHERE Conditions]

[ORDER BY Expression [ASC | DESC]];

Parameters or Arguments of SQL Server Top n Clause:


1. TOP (top_value): It Returns the top n number of records in the result set based
on top_value. For example, TOP(10) in the select query will return the top 10 records
from the full result set.
2. PERCENT: It is optional. If we specified the PERCENT, then the top rows are returned
based on the percentage of the total result set. For example, if we specify TOP (10)
PERCENT in the select query then it will return the top 10% of the records from the full
result set.
3. WITH TIES: It is optional. If we specify the “WITH TIES” clause, then rows tied in the
last place within the limited result set are returned.
4. Expressions: This is nothing but the columns or calculations that we want to retrieve.
5. Tables: The table names from which you want to retrieve the data. There should be at
least one table specified in the FROM clause on the query.
6. WHERE conditions: It is Optional. If you want to retrieve the data based on some
conditions then you need to specify the conditions using this where clause.
7. ORDER BY: It is also optional. If you want to retrieve the top records either from
ascending or descending order of certain column(s) then you need to use this Order By
Clause.

Example to understand TOP N CLAUSE in SQL Server:


Let us understand the use of the top n clause in SQL Server with examples. We are going
to use the following Employee table to understand the TOP n clause in SQL Server.
Please use the below SQL Script to create and populate the Employee table with the
required data.

-- Create Employee table

CREATE TABLE Employee

ID INT PRIMARY KEY IDENTITY(1,1),

Name VARCHAR(100),

EmailID VARCHAR(100),

Gender VARCHAR(100),

Department VARCHAR(100),

Salary INT,

Age INT,

CITY VARCHAR(100)

GO

--Insert data into Employee table

INSERT INTO Employee VALUES('PRANAYA','PRANAYA@G.COM','Male', 'IT',


25000, 30,'MUMBAI')

INSERT INTO Employee VALUES('TARUN','TARUN@G.COM','Male', 'Payroll', 30000,


27,'ODISHA')

INSERT INTO Employee VALUES('PRIYANKA','PRIYANKA@G.COM','Female', 'IT',


27000, 25,'BANGALORE')

INSERT INTO Employee VALUES('PREETY','PREETY@G.COM','Female', 'HR', 35000,


26,'BANGALORE')

INSERT INTO Employee VALUES('RAMESH','RAMESH@G.COM','Male','IT', 26000,


27,'MUMBAI')
INSERT INTO Employee VALUES('PRAMOD','PRAMOD@G.COM','Male','HR', 29000,
28,'ODISHA')

INSERT INTO Employee VALUES('ANURAG','ANURAG@G.COM','Male', 'Payroll',


27000, 26,'ODISHA')

INSERT INTO Employee VALUES('HINA','HINA@G.COM','Female','HR', 26000,


30,'MUMBAI')

INSERT INTO Employee VALUES('SAMBIT','HINA@G.COM','Male','Payroll', 30000,


25,'ODISHA')

GO

Using TOP n Clause in SQL Server with Examples


In the below example, we are using the TOP(3) clause to selects the first 3 records from the
Employee table where Gender is Male. If there are other records in the Employee table
whose Gender is Male then those records will not be returned by the SELECT statement
.
SELECT TOP(3)

ID, Name, EmailID, Gender, CITY, Department

FROM Employee

WHERE Gender = 'Male'

ORDER BY ID;

In our Employee Table, a total of 6 Employees are there whose Gender is male but in our
example, as we are using the Top (3) clause it only returns the top 3 records from the
Employee table order by ID ascending. So, when you will execute the above query, you will
get the following output.

Using TOP PERCENT keyword in SQL Server:


Let us see how to use the TOP PERCENT keyword in SQL Server. The below example
uses the TOP PERCENT keyword to select the first 70% of the records from the full result
set. So in the below example, the SELECT statement would return the top 70% of the
records from the Employee table where the Gender is Male. The other 30% of the result set
would not be returned by the SELECT statement.

SELECT TOP (70) PERCENT

ID, Name, EmailID, Gender, CITY, Department

FROM Employee

WHERE Gender = 'Male'

ORDER BY ID;

So, when you execute the above query, you will get the following output.

Using TOP with TIES in SQL Server:


The TOP with TIES clause would include rows that may be tied in the last place within the
limited result set. So let us understand the TOP with TIES Clause in SQL Server with an
example. The TOP with TIES can be used only with the following clause:
1. Select Statement
2. Order by clause is necessary for using this clause
3. PERCENT clause

Example:
We are going to use the following Person table to understand this concept.
Please use the below SQL Script to create and populate the Person table with the
required test data.
CREATE TABLE Person

ID INT PRIMARY KEY IDENTITY(1,1),

Name VARCHAR(50),

Salary int

GO

INSERT INTO Person VALUES('PRANAYA', 20000)

INSERT INTO Person VALUES('KUMAR', 30000)

INSERT INTO Person VALUES('ROUT', 25000)

INSERT INTO Person VALUES('PRANAYA', 25000)

INSERT INTO Person VALUES('KUMAR', 30000)

INSERT INTO Person VALUES('ROUT', 25000)

INSERT INTO Person VALUES('PRIYANKA', 20000)

INSERT INTO Person VALUES('PREETY', 30000)

GO

As we already discussed the Select TOP N query always returns exactly N number of
records. The following example will return the TOP 3 records from the Person table.

SELECT TOP (3) Name FROM Person

ORDER BY Name
Problem
In the above example, we have a situation in which the top clause returns exactly N number
records and drops the records which have the same value as the last record fetched in the
result set. In the above Person table we have two employees with the name PRANAYA but
both the Name PRANAYA will not be in the result since they are ignored by the TOP clause.

Select Query Using TOP with TIES Clause


SELECT TOP (3) WITH TIES Name FROM Person ORDER BY Name ASC

WITH TIES using TOP N PERCENT


SELECT TOP (30) PERCENT Name FROM Person ORDER BY Name ASC

SELECT TOP (30) PERCENT WITH TIES Name FROM Person ORDER BY Name ASC

TOP n Clause with Update Statement: UPDATE TOP (3) Person SET Salary = 72000
TOP n Clause with Delete statement: DELETE TOP (2) FROM Person

4. Group By Clause in SQL Server


Group By Clause in SQL Server
The Group by Clause in SQL Server is used to divide similar types of records or data as a
group and then return. If we use group by clause in the query then we should use
grouping/aggregate function such as count(), sum(), max(), min(), and avg() functions.
When we implement group by clause first the data of the table will be divided into
the separate group as per the column and later aggregate function will execute on each
group data to get the result. That means first Group By clause is used to divide similar types
of data as a group and then an aggregate function is applied to each group to get the
required results.

Syntax of Group By Clause in SQL Server


SELECT expression1, expression2, expression_n,

aggregate_function (expression)

FROM tables

[WHERE conditions]

GROUP BY expression1, expression2, expression_n;

Parameters or Arguments used in Group By Clause in SQL Server:


1. expression1, expression2, expression_n: The expressions that are not
encapsulated within an aggregate function must be included in the GROUP BY
clause.
2. aggregate_function: The aggregate function is nothing but such as
SUM, COUNT, MIN, MAX, or AVG functions that we should use while we are using the
Group by Clause in SQL Server.
3. Tables: Tables are nothing but the name of the table or tables from which we want to
retrieve the data.
4. WHERE conditions: It is optional. If you want to retrieve the data based on some
conditions then you need to specify such conditions using the Where Clause in SQL
Server.

Example to Understand Group By Clause in SQL Server


Let us understand SQL Server Group By Clause with Examples. We are going to use the
following Employee table to understand the Group By Clause in SQL Server with Examples.
Please use the below SQL Script to create and populate the Employee table with sample
data that we are going to use in this article.
-- Create Employee table

CREATE TABLE Employee

ID INT PRIMARY KEY IDENTITY(1,1),

Name VARCHAR(100),

EmailID VARCHAR(100),

Gender VARCHAR(100),

Department VARCHAR(100),

Salary INT,

Age INT,

CITY VARCHAR(100)

GO

--Insert data into Employee table


INSERT INTO Employee VALUES('PRANAYA','PRANAYA@G.COM','Male', 'IT',
25000, 30,'MUMBAI')

INSERT INTO Employee VALUES('TARUN','TARUN@G.COM','Male', 'Payroll', 30000,


27,'ODISHA')

INSERT INTO Employee VALUES('PRIYANKA','PRIYANKA@G.COM','Female', 'IT',


27000, 25,'BANGALORE')

INSERT INTO Employee VALUES('PREETY','PREETY@G.COM','Female', 'HR', 35000,


26,'BANGALORE')

INSERT INTO Employee VALUES('RAMESH','RAMESH@G.COM','Male','IT', 26000,


27,'MUMBAI')

INSERT INTO Employee VALUES('PRAMOD','PRAMOD@G.COM','Male','HR', 29000,


28,'ODISHA')

INSERT INTO Employee VALUES('ANURAG','ANURAG@G.COM','Male', 'Payroll',


27000, 26,'ODISHA')

INSERT INTO Employee VALUES('HINA','HINA@G.COM','Female','HR', 26000,


30,'MUMBAI')

INSERT INTO Employee VALUES('SAMBIT','HINA@G.COM','Male','Payroll', 30000,


25,'ODISHA')

INSERT INTO Employee VALUES('MANOJ','MANOJ@G.COM','Male','HR', 30000,


28,'ODISHA')

INSERT INTO Employee VALUES('SWAPNA','SWAPNA@G.COM','Female', 'Payroll',


28000, 27,'MUMBAI')

INSERT INTO Employee VALUES('LIMA','LIMA@G.COM','Female','HR', 30000,


30,'BANGALORE')

INSERT INTO Employee VALUES('DIPAK','DIPAK@G.COM','Male','Payroll', 32000,


25,'BANGALORE')

GO
WAQ to find total employees in the organization.
SELECT COUNT(*) AS TotalEmployee FROM Employee

WAQ to find the number of employees working in each department in the company.
Here, we need to group the employees by department, and then we need to apply the count
function to each group. The following SQL query exactly does the same.

SELECT Department, COUNT(*) AS TotalEmployee

FROM Employee

GROUP BY Department

When we execute the above query, it gives us the below output.

Note: If we use Group By Clause in a query, first the data in the table will be divided into
different groups based on the column specified in the group by clause and then execute the
aggregate function on each group to get the results
.
WAQ to find the total salary in each department of the organization.
SELECT Department, TotalSalary = SUM(Salary)

FROM Employee

GROUP BY Department
When we execute the above query, it gives us the below output.

WAQ to find the highest salary in each department in the organization.


SELECT Department, MaxSalary = MAX(SALARY)

FROM Employee

GROUP BY Department
When we execute the above query, it gives us the below output.
While working with the group by clause in a query we need to follow or consider the
following
1. When the aggregate function is applied to a group it returns only a single value but
each group can return a value.
2. Use Group By clause only on a column that contains duplicate values, never applies
it on unique columns.

Write a query to get the number of employees working in each Gender per
department.
SELECT Department, Gender, EmployeeCount = COUNT(*)

FROM Employee

GROUP BY Department, Gender

ORDER BY Department

When we execute the above query, it gives us the below output.

When we use multiple columns in a group by clause first data in the table is divided based
on the first column of the group by clause and then each group is subdivided based on the
second column of the group by clause and then the group function is applied on each inner
group to get the result.
Write a query to get the highest salary for the organization.
SELECT MAX(Salary) as MaxSalary FROM Employee
Write a Query for retrieving total salaries by the city.
We are applying the SUM() aggregate function on the Salary column, and grouping by city
column. This effectively adds all the salaries of employees within the same city.

SELECT CITY, SUM(Salary) as TotalSalary

FROM Employee

GROUP BY CITY

When we execute the above query, it gives us the following output.

Note: If you omit, the group by clause and try to execute the query, you get an error –

Write a Query for retrieving total salaries by city and by gender.


It’s possible to group by multiple columns. In this query, we are grouping first by city and
then by gender.
SELECT CITY, Gender, SUM(Salary) as TotalSalary

FROM Employee

GROUP BY CITY, Gender

When we execute the above query, it gives us the below output.


Write a Query for retrieving total salaries and the total number of employees by City,
and by gender.
The only difference here is that, we are using Count() aggregate function.

SELECT City, Gender, SUM(Salary) as TotalSalary,

COUNT(ID) as TotalEmployees

FROM Employee

GROUP BY CITY, Gender

Write a query to find out the highest salary of each department along with the name
of the employee.
SELECT Department, MAX(Salary) as Salary, Name

FROM Employee

GROUP BY Department – Invalid

It will give the error as Column ‘Employee.Name’ is invalid in the select list because it
is not contained in either an aggregate function or the GROUP BY clause.

Note: The above query will not be executed because using group by clause in a statement
the select list can contain only three things
1. Columns that are associated with the GROUP BY clause.
2. Aggregate or GROUP functions
3. Constants

In our above query Name column does not fall under any of the three so it cannot be used
in the select list.
SELECT Department, MAX(Salary) as Salary, Name

FROM Employee

GROUP BY Department -- Invalid


SELECT Department, MAX(SALARY), GETDATE()

FROM Employee

GROUP BY Department --Valid

SELECT Department, Gender, MAX(Salary), 'Hello' as FixedValue

FROM Employee

GROUP BY Department, Gender --Valid

5.Having Clause in SQL Server

What is Having Clause and its need in SQL Server?


The Having Clause in SQL Server is used for restricting or you can say filtering the data
just like the where clause in SQL Server. So, the Having Clause in SQL Server is an
additional filter that is applied to the result set. Logically, the having clause filters the rows
from the intermediate result set that is built by using the FROM, WHERE, or GROUP BY
clauses in the SELECT statement.
The Having clause is typically used with a GROUP BY clause. That means it is used in
combination with a GROUP BY clause to restrict the number of groups to be returned by
satisfying the condition which is specified using the having clause.

Syntax of SQL Server Having Clause:


SELECT expression1, expression2, expression_n,

aggregate_function (expression)

FROM tables

[WHERE conditions]

GROUP BY expression1, expression2, expression_n

HAVING having_condition;
Parameters or Arguments of Having Clause in SQL Server:
1. aggregate_function: It can be any of the aggregate functions such as SUM,
COUNT, MIN, MAX, or AVG.
2. expression1, expression2, expression_n: The expressions which are not
encapsulated within an aggregate function must be included in the GROUP BY clause.
3. Where Conditions: It is optional. If you want to retrieve selected records based on
some conditions then you need to specify the conditions using the Where clause in SQL
Server.
4. HAVING having_condition: The Having Clause Condition is used to add a further
condition that can be applied only to the aggregated results to restrict the number of
groups to be returned.

Database tables used in this demo:


We are going to use the following Employee table in this demo.

Please use the below script to create and populate the Employee table with some
dummy data.

-- Create Person table

CREATE TABLE Employee

ID INT PRIMARY KEY IDENTITY(1,1),

Name VARCHAR(100),
EmailID VARCHAR(100),

Gender VARCHAR(100),

Department VARCHAR(100),

Salary INT,

Age INT,

CITY VARCHAR(100)

GO

--Insert some test data into Person table

INSERT INTO Employee VALUES('PRANAYA','PRANAYA@G.COM','Male', 'IT',


25000, 30,'MUMBAI')

INSERT INTO Employee VALUES('TARUN','TARUN@G.COM','Male', 'Payroll', 30000,


27,'ODISHA')

INSERT INTO Employee VALUES('PRIYANKA','PRIYANKA@G.COM','Female', 'IT',


27000, 25,'BANGALORE')

INSERT INTO Employee VALUES('PREETY','PREETY@G.COM','Female', 'HR', 35000,


26,'BANGALORE')

INSERT INTO Employee VALUES('RAMESH','RAMESH@G.COM','Male','IT', 26000,


27,'MUMBAI')

INSERT INTO Employee VALUES('PRAMOD','PRAMOD@G.COM','Male','HR', 29000,


28,'ODISHA')

INSERT INTO Employee VALUES('ANURAG','ANURAG@G.COM','Male', 'Payroll',


27000, 26,'ODISHA')

INSERT INTO Employee VALUES('HINA','HINA@G.COM','Female','HR', 26000,


30,'MUMBAI')
INSERT INTO Employee VALUES('SAMBIT','HINA@G.COM','Male','Payroll', 30000,
25,'ODISHA')

INSERT INTO Employee VALUES('MANOJ','MANOJ@G.COM','Male','HR', 30000,


28,'ODISHA')

INSERT INTO Employee VALUES('SWAPNA','SWAPNA@G.COM','Female', 'Payroll',


28000, 27,'MUMBAI')

INSERT INTO Employee VALUES('LIMA','LIMA@G.COM','Female','HR', 30000,


30,'BANGALORE')

INSERT INTO Employee VALUES('DIPAK','DIPAK@G.COM','Male','Payroll', 32000,


25,'BANGALORE')

GO

Filtering Groups in SQL Server:


The Where clause in SQL Server is used to filter the rows before aggregation, whereas the
Having clause in SQL Server is used to filter the groups that mean after aggregations. The
following 2 queries produce the same result.

Filtering rows using WHERE clause


SELECT City, SUM(Salary) as TotalSalary

FROM Employee

WHERE City = 'MUMBAI'

GROUP BY City

Filtering groups using the HAVING clause, after all, aggregations take place.
SELECT City, SUM(Salary) as TotalSalary

FROM Employee

GROUP BY City

HAVING City = 'MUMBAI'

From the performance point of view, we cannot say or we cannot give a guarantee that one
method is more efficient than the other one. The SQL Server optimizer checks or analyzes
each statement and then selects an efficient way of executing the query. So, try to eliminate
the records as soon as possible which you don’t want in your result set.
It is also possible to combine WHERE and HAVING

SELECT City, SUM(Salary) as TotalSalary

FROM Employee

WHERE Gender = 'Male'

GROUP BY City

HAVING City = 'MUMBAI'

Having Clause Using SUM Function:


The below example uses the SUM function to return the name of the department and the
total Salary (associated with the department). The Having Clause will filter the results so
that only departments with a total Salary greater than 140000 will be returned.

SELECT Department, SUM(Salary) AS Total_Salary

FROM Employee

GROUP BY Department

HAVING SUM(Salary) > 140000;

Having Clause Using COUNT Function:


The below example uses the COUNT function to return the city and the number of
employees (residing in that city). The Having Clause will filter the results so that only cities
with more than 4 employees will be returned.

SELECT City, COUNT(*) AS 'Number of employees'

FROM Employee
GROUP BY City

HAVING COUNT(*) > 4;

Having Clause Using MIN Function:


The below example uses the MIN function to return the name of each department and the
minimum salary in the department. The Having Clause will return only those departments
where the minimum salary is greater than 25000
.
SELECT Department, MIN(Salary) AS 'Lowest salary'

FROM Employee

GROUP BY Department

HAVING MIN(Salary) > 25000;

Having Clause Using MAX Function:


The below example uses the MAX function to return the name of each department and the
maximum salary in each department. The Having Clause will return only those departments
where the maximum salary is greater than 27000.
SELECT Department, MAX(Salary) AS 'Highest salary'

FROM Employee

GROUP BY Department

HAVING MAX(Salary) > 27000;


Having Clause Using AVG Function:
The below example uses the AVG function to return the name of each department and the
Average salary of each department. Having clause will return only those departments where
the average salary is greater than 27000.
SELECT Department, AVG(Salary) AS 'Average salary'

FROM Employee

GROUP BY Department

HAVING AVG(Salary) > 27000;

6.Difference Between Where and Having Clause in SQL Server

Let us understand the Difference Between Where and Having Clause in SQL
Server with an example. For this demo, I am going to use the following Sales table.

Please use the following SQL Script to create and populate the Sales table with test
data
Create table Sales

Product nvarchar(50),

SaleAmount int

)
Go

Insert into Sales values ('iPhone', 500)

Insert into Sales values ('Laptop', 800)

Insert into Sales values ('iPhone', 1000)

Insert into Sales values ('Speakers', 400)

Insert into Sales values ('Laptop', 600)

Go

Example:
To calculate total sales by-product, we would write a GROUP BY query as shown below
SELECT Product, SUM(SaleAmount) AS TotalSales

FROM Sales

GROUP BY Product

Now if we want to find only those products where the total sales amount is greater than
$1000, we will use the HAVING clause to filter products as shown in the below SQL query

SELECT Product, SUM(SaleAmount) AS TotalSales

FROM Sales

GROUP BY Product

HAVING SUM(SaleAmount) > 1000

If we use the Where clause instead of the Having clause, then we will get a syntax error.
The reason is the Where clause in SQL Server will not work with the aggregate functions
such as sum, min, max, avg, etc.
SELECT Product, SUM(SaleAmount) AS TotalSales

FROM Sales

GROUP BY Product

WHERE SUM(SaleAmount) > 1000

When we execute the above query it will give us the error as Incorrect syntax near the
keyword ‘WHERE’.
So, in short, the difference is the WHERE clause cannot be used with aggregate
function whereas the HAVING clause can. The Where clause filters rows before aggregate
calculations are performed whereas the HAVING clause filters rows after aggregate
calculations are performed. Let us understand this with an example.
We can calculate the Total sales of iPhones and Speakers using either the WHERE clause
or by using the HAVING clause. Calculate Total sales of iPhone and Speakers using
WHERE clause: In the below example, the WHERE clause retrieves only the products such
as iPhone and Speaker and then calculates the sum.

SELECT Product, SUM(SaleAmount) AS TotalSales

FROM Sales

WHERE Product in ('iPhone', 'Speakers')

GROUP BY Product

Now we are going to Calculate the Total sales of iPhone and Speakers by using the
HAVING clause: The following example retrieves all the rows from the Sales table, and then
only performs the sum operation. Once it performs the SUM operations then it removes all
products from the result set except the iPhone and Speakers.
SELECT Product, SUM(SaleAmount) AS TotalSales

FROM Sales

GROUP BY Product

HAVING Product in ('iPhone', 'Speakers')


So, from the performance point of view, the HAVING is slower than the WHERE clause, and
the having clause should be avoided if possible.

Difference Between Where Clause and Having Clause in SQL Server


1. WHERE clause cannot be used with aggregate functions whereas HAVING clause
can be used with aggregate functions. This means the WHERE clause is used for
filtering individual rows on a table whereas the HAVING clause is used to filter
groups.
2. WHERE comes before GROUP BY. This means the WHERE clause filters rows
before aggregate calculations are performed. HAVING comes after GROUP BY. This
means the HAVING clause filters groups after aggregate calculations are performed.
So, from a performance standpoint, HAVING is slower than WHERE and should be
avoided when possible.
3. WHERE and HAVING clauses can be used together in a SELECT query. In this case
WHERE clause is applied first to filter individual rows. The rows are then grouped
and aggregate calculations are performed, and then the HAVING clause filters the
groups.
4. WHERE clause can be used with – Select, Insert, and Update statements whereas
HAVING clause can only be used with the Select statement

You might also like