You are currently viewing How to Filter Data From Table in SQL Server

How to Filter Data From Table in SQL Server

How to Filter Data From Table in SQL Server

WHERE clause is used to filter data according to specified conditions. It is used with SELECT, UPDATE, and DELETE statements. WHERE clause is not only used with a single table but it can also be used with multiple tables.

For this demo, we create the tblEmployee table and then see how the WHERE clause works.

CREATE TABLE tblEmployee
(
	EmpID INT PRIMARY KEY NOT NULL,
	EmpFirstName NVARCHAR(20) NOT NULL,
	EmpLastName NVARCHAR(20) NOT NULL,
	EmpAge INT NULL,
	EmpGender NVARCHAR(10) NULL,
	EmpEmail NVARCHAR(50) NULL,
	EmpPhone NVARCHAR(20) NULL,
	EmpSalary INT NULL,
	EmpJoiningDate DATETIME NULL
)
GO

Let’s insert some rows in the table tblEmployee.

INSERT INTO tblEmployee
    (EmpID, EmpFirstName,EmpLastName,EmpAge,EmpGender,EmpEmail,EmpPhone,EmpSalary,EmpJoiningDate)
VALUES
    (1,'john','dave',26,'male','john@gmail.com','0923044554561',26000,'2010-02-01'),
    (2,'kamran','akmal',35,'male','kami@gmail.com','0923044545562',25000,'2011-01-01'),
    (3,'umar','akmal',36,'male','umar@gmail.com','0923044554563',38000,'2015-01-01'),
    (4,'thomas','hardy',36,'male','thomas@gmail.com','0923044554564',25000,'2016-05-05'),
    (5,'amar','sidhu',36,'male','amar@gmail.com','0923044554560',25000,'2016-05-05'),
    (6,'simran','sidhu',25,'female','simran@gmail.com','0923044554565',33000,'2018-01-01'),
    (7,'diyana','jeni',26,'female','diyana@gmail.com','0923044554566',50000,'2005-01-01'),
    (8,'maria','anders',27,'female','maria@gmail.com','0923044554567',70000,'2004-01-01'),
    (9,'anam','chaudhary',29,'female','anam@gmail.com','0923044554568',25000,'2020-01-01'),
    (10,'Amelia','sidhu',56,'female','amelia@gmail.com','0923044554569',50000,'2015-01-01')
    GO
    

See the table with data in the below image.

WHERE Clause with SELECT Statement

WHERE clause can be used with a SELECT Statement to fetch data from a table based on the specified condition. Let’s fetch the second record whose EmpID is 2.

SELECT * FROM tblEmployee WHERE EmpID = 2

We get the result as below.

WHERE Clause with UPDATE Statement

WHERE clause can be used with a UPDATE Statement to update data in a table based on the specified condition. Let’s update the second record, whose EmpID is 2.

UPDATE tblEmployee SET EmpFirstName='Ali', EmpEmail='Ali@gmail.com'
WHERE EmpID = 2
    

We can see the updated EmpFirstName  and EmpEmail whose EmpID is 2 as below.

WHERE clause with DELETE Statement

WHERE clause can be used with a DELETE Statement to delete data from a table based on the specified condition. Let’s delete the second record, whose EmpID is 2.

DELETE FROM tblEmployee WHERE EmpID = 2

We can see that the record with EmpID 2 deleted and is not available in tblEmployee table as shown in below image.

Recommended Readings