SQL Server-2 - Clauses
SQL Server-2 - Clauses
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.
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.
Gender VARCHAR(50)
GO
(
ID INT PRIMARY KEY IDENTITY(1,1),
Name VARCHAR(100)
Name VARCHAR(100),
EmailID VARCHAR(100),
GenderID INT,
DepartmentID INT,
Salary INT,
Age INT,
CITY VARCHAR(100)
GO
REFERENCES Gender(ID)
GO
GO
GO
GO
GO
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.
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.
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.
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.
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.
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.
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.
Name VARCHAR(100),
EmailID VARCHAR(100),
Gender VARCHAR(100),
Department VARCHAR(100),
Salary INT,
Age INT,
CITY VARCHAR(100)
GO
GO
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.
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.
FROM Employee
When you execute the above query, you will get the following output. Notice, it will skip the
first 5 records in the result set.
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.
When you will execute the above query, you will get the first 5 records of the result set as
shown in the below image.
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.
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]
Name VARCHAR(100),
EmailID VARCHAR(100),
Gender VARCHAR(100),
Department VARCHAR(100),
Salary INT,
Age INT,
CITY VARCHAR(100)
GO
GO
FROM Employee
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.
FROM Employee
ORDER BY ID;
So, when you execute the above query, you will get the following output.
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
Name VARCHAR(50),
Salary int
GO
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.
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 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
aggregate_function (expression)
FROM tables
[WHERE conditions]
Name VARCHAR(100),
EmailID VARCHAR(100),
Gender VARCHAR(100),
Department VARCHAR(100),
Salary INT,
Age INT,
CITY VARCHAR(100)
GO
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.
FROM Employee
GROUP BY Department
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.
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
ORDER BY Department
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.
FROM Employee
GROUP BY CITY
Note: If you omit, the group by clause and try to execute the query, you get an error –
FROM Employee
COUNT(ID) as TotalEmployees
FROM Employee
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
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
FROM Employee
FROM Employee
aggregate_function (expression)
FROM tables
[WHERE conditions]
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.
Please use the below script to create and populate the Employee table with some
dummy data.
Name VARCHAR(100),
EmailID VARCHAR(100),
Gender VARCHAR(100),
Department VARCHAR(100),
Salary INT,
Age INT,
CITY VARCHAR(100)
GO
GO
FROM Employee
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
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
FROM Employee
GROUP BY City
FROM Employee
GROUP BY Department
FROM Employee
GROUP BY City
FROM Employee
GROUP BY Department
FROM Employee
GROUP BY Department
FROM Employee
GROUP BY Department
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
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
FROM Sales
GROUP BY Product
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
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.
FROM Sales
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