How to Select a Range of Letters in SQL?
In this article, we will see how to Select a Range of Letters in SQL using the LIKE clause. The LIKE clause is used for pattern matching in SQL using wildcard operators such as %, ^, etc. It has square brackets[] as one of the wildcard operators that is used to specify the range of characters for pattern matching.
Let see these above mention function with an example. For the demonstration follow the following steps:
Step 1: Create a database
Use the below SQL statement to create database called geeks;
Query:
CREATE DATABASE geeks;
Step 2: Using the database
Use the below SQL statement to switch the database context to geeks:
Query:
USE geeks;
Step 3: Table creation
We have the following demo_table in our geek’s database.
Query:
CREATE TABLE demo_table( NAME VARCHAR(20), AGE INT, CITY VARCHAR(20) );
Step 4: Insert data into a table
Query:
INSERT INTO demo_table VALUES ('ROMY KUMARI', 22, 'NEW DELHI'), ('PUSHKAR JHA',23, 'NEW DELHI'), ('RINKLE ARORA',23, 'PUNJAB'), ('AKASH GUPTA', 23, 'UTTAR PRADESH'), ('AKANKSHA GUPTA',22, 'PUNJAB'), ('SUJATA JHA', 30,'PATNA');
Step 5: View data of the table
Query:
SELECT * FROM demo_table;
Output:
Step 6: use of LIKE clause to select range of letters
Syntax to use wildcard operators
SELECT * from tablename WHERE column_name LIKE '%[range_value]%';
‘%’ is a wildcard character that specifies 0 or more characters.
For demonstration:
- Select rows from table whose name start with values in range O-S (O to S).
Query:
SELECT * FROM demo_table WHERE NAME LIKE '[O-S]%';
Output:
- Select rows from table whose AGE is the range 22-25.
Query:
SELECT * FROM demo_table WHERE AGE LIKE '[22-25]%';
Output:
Please Login to comment...