SQL WHERE Clause – Adding a condition using SQL

WHERE clause is used to define limit requirements for queries. We are not interested in all records in most cases of queries into tables. Only some subsets of the records based on set criteria are of our interest.

Order of WHERE Clause in SQL Script

  1. SELECT
  2. FROM
  3. WHERE
  4. GROUP BY
  5. HAVING
  6. ORDER BY

Syntax

SELECT [Column 1], [Column 2]
FROM Tabule
WHERE Column <Operator>
value;

SQL Operators in WHERE clause

We will take a look at all SQL operators in a separate chapter. Below you can see the list of simple comparison operators which we work with whenever we need to filter data.

  • = Equals to
  • <> Does not equal to
  • < Is lower than
  • <= Is lower than or equal to
  • > Is higher
  • >= Is higher or equal to

Example of  WHERE Clause Usage with BETWEEN operator and >= <= operators

The table which we will use is shown below. It consists of 18484 records.

Dimcustomer-pred-WHERE-klauzuli

We use clause to filter all customers whose birthday is between 1920-01-01 a 1921-12-31 including. We have two options and the results will be the same.

(i) The first option is to use BETWEEN operator. Marginal dates are included in the requirement.

--Option 1
SELECT [CustomerKey]
,[FirstName]
,[LastName]
,[BirthDate]
FROM [AdventureWorksDW2012].[dbo].[DimCustomer]
WHERE BirthDate BETWEEN '1920-01-01' AND '1921-12-31';

(ii) second option is to use operators <= and >= operators

--Option 2
SELECT [CustomerKey]
,[FirstName]
,[LastName]
,[BirthDate]
FROM [AdventureWorksDW2012].[dbo].[DimCustomer]
WHERE BirthDate >= '1920-01-01' AND BirthDate<=
'1921-12-31';

The result is 5 records of customers born between 1.1.1920 and 31.12.1921.

Vysledek po omezeni SQL WHERE

For more information, see the official Microsoft documentation

Rate this post
Category: SQL Basics SQL Clauses

About Ing. Jan Zedníček - Data Engineer & Controlling

My name is Jan Zednicek, and I have been working as a freelance Data Engineer for roughly 10 years. During this time, I have been publishing case studies and technical guides on this website, targeting professionals, students, and enthusiasts interested in Data Engineering particularly on Microsoft technologies as well as corporate finance and reporting solutions. 🔥 If you found this article helpful, please share it or mention me on your website or Community forum

Leave a Reply

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