The Wayback Machine - https://web.archive.org/web/20241001065706/https://www.geeksforgeeks.org/sql-where-clause/
Open In App

SQL | WHERE Clause

Last Updated : 12 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

WHERE keyword is used for fetching filtered data in a result set. It is used to fetch data according to particular criteria. WHERE keyword can also be used to filter data by matching patterns.

Syntax:

SELECT column1,column2 FROM table_name WHERE column_name operator value;

Parameter Explanation:

  1. column1,column2: fields in the table
  2. table_name: name of table
  3. column_name: name of field used for filtering the data
  4. operator: operation to be considered for filtering
  5. value: exact value or pattern to get related data in result 

List of Operators that Can be Used with WHERE Clause

Operator Description
> Greater Than
>= Greater than or Equal to
< Less Than
<= Less than or Equal to
= Equal to
<> Not Equal to
BETWEEN In an inclusive Range
LIKE Search for a pattern
IN To specify multiple possible values for a column

Query:

CREATE TABLE Emp1(
EmpID INT PRIMARY KEY,
Name VARCHAR(50),
Country VARCHAR(50),
Age int(2),
mob int(10)
);
-- Insert some sample data into the Customers table
INSERT INTO Emp1 (EmpID, Name,Country, Age, mob)
VALUES (1, 'Shubham', 'India','23','738479734'),
(2, 'Aman ', 'Australia','21','436789555'),
(3, 'Naveen', 'Sri lanka','24','34873847'),
(4, 'Aditya', 'Austria','21','328440934'),
(5, 'Nishant', 'Spain','22','73248679');
Select * from Emp1;

Where Clause with Logical Operators

To fetch records of  Employee with ages equal to 24. 

Query:

SELECT * FROM Emp1 WHERE Age=24;

Output:

Image

 

To fetch the EmpID, Name and Country of Employees with Age greater than 21. 

Query:

SELECT EmpID, Name, Country FROM Emp1 WHERE Age > 21;

Output:

Image

 

Where Clause with BETWEEN Operator

It is used to fetch filtered data in a given range inclusive of two values. 

Syntax: 

SELECT column1,column2 FROM table_name 

WHERE column_name BETWEEN value1 AND value2;

Parameter Explanation:

  1. BETWEEN: operator name 
  2. value1 AND value2: exact value from value1 to value2 to get related data in result set.  

To fetch records of Employees where Age is between 22 and 24 (inclusive).

Query:

SELECT * FROM Emp1 WHERE Age BETWEEN 22 AND 24;

Output:

Image

 

Where Clause with LIKE Operator

It is used to fetch filtered data by searching for a particular pattern in the where clause. 

Syntax: 

SELECT column1,column2 FROM

table_name WHERE column_name LIKE pattern;

Parameters Explanation:

  1. LIKE: operator name 
  2. pattern: exact value extracted from the pattern to get related data in the result set. 

Note: The character(s) in the pattern is case-insensitive.

To fetch records of Employees where Name starts with the letter S.

Query:

SELECT * FROM Emp1 WHERE Name LIKE 'S%'; 

The ‘%'(wildcard) signifies the later characters here which can be of any length and value. 

Output:

Image

 

To fetch records of Employees where Name contains the pattern ‘M’.

Query:

SELECT * FROM Emp1 WHERE Name LIKE '%M%';

Output:

Image

 

Where Clause with IN Operator

It is used to fetch the filtered data same as fetched by ‘=’ operator just the difference is that here we can specify multiple values for which we can get the result set.

Syntax: 

SELECT column1,column2 FROM table_name WHERE column_name IN (value1,value2,..);

Parameters Explanation:

  1. IN: operator name 
  2. value1,value2,..: exact value matching the values given and get related data in the result set.

To fetch the Names of Employees where Age is 21 or 23.

Query:

SELECT Name FROM Emp1 WHERE Age IN (21,23);

Output:

Image


Previous Article
Next Article

Similar Reads

SQL | Intersect & Except clause
1. INTERSECT clause : As the name suggests, the intersect clause is used to provide the result of the intersection of two select statements. This implies the result contains all the rows which are common to both the SELECT statements. Syntax : SELECT column-1, column-2 …… FROM table 1 WHERE….. INTERSECT SELECT column-1, column-2 …… FROM table 2 WHE
1 min read
SQL | Sub queries in From Clause
From clause can be used to specify a sub-query expression in SQL. The relation produced by the sub-query is then used as a new relation on which the outer query is applied. Sub queries in the from clause are supported by most of the SQL implementations.The correlation variables from the relations in from clause cannot be used in the sub-queries in
2 min read
SQL | ON Clause
The join condition for the natural join is basically an EQUIJOIN of all columns with same name. To specify arbitrary conditions or specify columns to join, the ON Clause is used. The join condition is separated from other search conditions. The ON Clause makes code easy to understand. ON Clause can be used to join columns that have different names.
2 min read
SQL Distinct Clause
The distinct keyword is used in conjunction with the select keyword. It is helpful when there is a need to avoid duplicate values present in any specific columns/table. When we use distinct keywords only the unique values are fetched. Syntax: SELECT DISTINCT column1, column2 FROM table_name Parameters Used: column1, column2: Names of the fields of
3 min read
SQL | Union Clause
The Union Clause is used to combine two separate select statements and produce the result set as a union of both select statements. NOTE: The fields to be used in both the select statements must be in the same order, same number, and same data type.The Union clause produces distinct values in the result set, to fetch the duplicate values too UNION
3 min read
SQL | Except Clause
In SQL, EXCEPT returns those tuples that are returned by the first SELECT operation, and not returned by the second SELECT operation. This is the same as using a subtract operator in relational algebra. Example: Say we have two relations, Students and TA (Teaching Assistant). We want to return all those students who are not teaching assistants. The
1 min read
PostgreSQL - ORDER BY clause
The PostgreSQL ORDER BY clause is used to sort the result query set returned by the SELECT statement. As the query set returned by the SELECT statement has no specific order, one can use the ORDER BY clause in the SELECT statement to sort the results in the desired manner. Syntax: SELECT column_1, column_2 FROM table_name ORDER BY column_1 [ASC | D
2 min read
SQL using Python and SQLite | Set 2
Databases offer numerous functionalities by which one can manage large amounts of information easily over the web, and high-volume data input and output over a typical file such as a text file. SQL is a query language and is very popular in databases. Many websites use MySQL. SQLite is a "light" version that works over syntax very much similar to S
3 min read
Program for Fibonacci numbers in PL/SQL
The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …….. In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation Fn = Fn-1 + Fn-1 with seed values F0= 0 and F1 = 1. Given a number n, print n-th Fibonacci Number. Input : n = 2 Output : 1 Inpu
1 min read
Check if a number is Palindrome in PL/SQL
Given an integer, write a function that returns true if the given number is palindrome, else false. For example, 12321 is palindrome, but 1451 is not palindrome. Let the given number be num. A simple method for this problem is to first reverse digits of num, then compare the reverse of num with num. If both are same, then return true, else false. E
1 min read
Prime number in PL/SQL
Prerequisite – PL/SQL introductionA prime number is a whole number greater than 1, which is only divisible by 1 and itself. First few prime numbers are : 2 3 5 7 11 13 17 19 23 …..In PL/SQL code groups of commands are arranged within a block. A block group-related declarations or statements. In declare part, we declare variables and between begin a
1 min read
Print pyramid of GeeksforGeeks in PL/SQL
PL/SQL is a block-structured language that enables developers to combine the power of SQL with procedural statements. All the statements of a block are passed to the oracle engine all at once which increases processing speed and decreases the traffic.PL/SQL extends SQL by adding constructs found in procedural languages, resulting in a structural la
2 min read
PL/SQL | User Input
Prerequisite - PL/SQL Introduction In PL/SQL, user can be prompted to input a value using & character. & can be used to prompt input for different data types. Consider, following table: Table: GFG id author likes 1 sam 10 2 maria 30 3 ria 40 Following queries will create a new table named GFG in the database. SQL> create table GFG (id nu
2 min read
Production databases in SQL queries
SQL is a Structured Query Language which is a computer language for storing, manipulating, and retrieving data stored in a relational database. SQL is the most powerful data handling tool. Actionable advice to help you get the most versatile language and create beautiful, effective queries. SQL is effectively used to insert, search, update, delete,
4 min read
SQL software and query optimization tools
Introduction : SQL stands for Structured Query Language. SQL is a non-procedural language, so the Optimizer is free to merge, reorganize and process in any order. It is based on statistics collected about accessed data. It is very useful to perform query and to store and manage data in RDBMS. SQL is a language to operate databases. It includes data
4 min read
Performing Database Operations in Java | SQL CREATE, INSERT, UPDATE, DELETE and SELECT
In this article, we will be learning about how to do basic database operations using JDBC (Java Database Connectivity) API in Java programming language. These basic operations are INSERT, SELECT, UPDATE, and DELETE statements in SQL language. Although the target database system is Oracle Database, the same techniques can be applied to other databas
6 min read
SQL | Aliases
Pre-Requisites:SQL table Aliases are the temporary names given to tables or columns for the purpose of a particular SQL query. It is used when the name of a column or table is used other than its original name, but the modified name is only temporary. Aliases are created to make table or column names more readable.The renaming is just a temporary c
3 min read
Basic SQL Injection and Mitigation with Example
SQL injection is a code injection technique, used to attack data driven applications, in which malicious SQL statements are inserted into an entry field for execution (e.g. to dump the database contents to the attacker). SQL Injection can be used in a range of ways to cause serious problems. By levering SQL Injection, an attacker could bypass authe
4 min read
SQL | CHECK Constraint
SQL Constraints Check Constraint is used to specify a predicate that every tuple must satisfy in a given relation. It limits the values that a column can hold in a relation. The predicate in check constraint can hold a sub query.Check constraint defined on an attribute restricts the range of values for that attribute.If the value being added to an
3 min read
SQL | MINUS Operator
The Minus Operator in SQL is used with two SELECT statements. The MINUS operator is used to subtract the result set obtained by first SELECT query from the result set obtained by second SELECT query. In simple words, we can say that MINUS operator will return only those rows which are unique in only first SELECT query and not those rows which are c
2 min read
How to use SQLMAP to test a website for SQL Injection vulnerability
This article explains how to test whether a website is safe from SQL injection using the SQLMAP penetration testing tool. What is SQL Injection? SQL Injection is a code injection technique where an attacker executes malicious SQL queries that control a web application's database. With the right set of queries, a user can gain access to information
6 min read
SQL | SEQUENCES
SQL sequences specifies the properties of a sequence object while creating it. An object bound to a user-defined schema called a sequence produces a series of numerical values in accordance with the specification used to create it. The series of numerical values can be configured to restart (cycle) when it runs out and is generated in either ascend
5 min read
SQL | CREATE DOMAIN
Used in : Postgre sql CREATE DOMAIN creates a new domain. A domain is essentially a data type with optional constraints (restrictions on the allowed set of values). The user who defines a domain becomes its owner. Domains are useful for abstracting common constraints on fields into a single location for maintenance. For example, several tables migh
1 min read
SQL Functions (Aggregate and Scalar Functions)
SQL Functions are built-in programs that are used to perform different operations on the database. There are two types of functions in SQL: Aggregate FunctionsScalar FunctionsSQL Aggregate FunctionsSQL Aggregate Functions operate on a data group and return a singular output. They are mostly used with the GROUP BY clause to summarize data.  Some com
4 min read
SQL Comments
SQL Comments explain sections of SQL statements or prevent SQL statements from being executed. There are 3 types of comments in SQL: Single-line commentsMulti-line commentsIn-line commentsThese are the three commenting methods in SQL, each with its unique use. Let's discuss these SQL comments in detail below: SQL Single Line CommentsSQL Single Line
3 min read
Features of C Programming Language
C is a procedural programming language. It was initially developed by Dennis Ritchie in the year 1972. It was mainly developed as a system programming language to write an operating system. The main features of C language include low-level access to memory, a simple set of keywords, and a clean style, these features make C language suitable for sys
3 min read
Data encryption standard (DES) | Set 1
This article talks about the Data Encryption Standard (DES), a historic encryption algorithm known for its 56-bit key length. We explore its operation, key transformation, and encryption process, shedding light on its role in data security and its vulnerabilities in today's context. What is DES?Data Encryption Standard (DES) is a block cipher with
15+ min read
Carrier Sense Multiple Access (CSMA)
This method was developed to decrease the chances of collisions when two or more stations start sending their signals over the data link layer. Carrier Sense multiple access requires that each station first check the state of the medium before sending. Prerequisite - Multiple Access Protocols Vulnerable Time: Vulnerable time = Propagation time (Tp)
6 min read
Carry Look-Ahead Adder
The adder produce carry propagation delay while performing other arithmetic operations like multiplication and divisions as it uses several additions or subtraction steps. This is a major problem for the adder and hence improving the speed of addition will improve the speed of all other arithmetic operations. Hence reducing the carry propagation de
5 min read
Phases of a Compiler
Prerequisite - Introduction of Compiler design We basically have two phases of compilers, namely the Analysis phase and Synthesis phase. The analysis phase creates an intermediate representation from the given source code. The synthesis phase creates an equivalent target program from the intermediate representation. A compiler is a software program
7 min read
Article Tags :
Practice Tags :