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

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

My name is Jan Zedníček and I have been working as a freelancer for many companies for more than 10 years. I used to work as a financial controller, analyst and manager at many different companies in field of banking and manufacturing. When I am not at work, I like playing volleyball, chess, doing a workout in the gym.

🔥 If you found this article helpful, please share it or mention me on your website

Leave a Reply

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