Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Where criteria to find names between A-F

Simple question:

I need a solution so that I can find, lets say names, between A-F, INCLUDING all names that start with F.

If you use BETWEEN or A >= value <= F you find out that it stops at F. So I am posting this for suggestions.

NOTE: User will see 2 textboxes that accept a range user can type. The user refines how far to go in F boundary as such: User types in 'Fa' means the result should return: Fauder, Fail, Famber, ... etc

I have currently 2 solutions but there's got a be a better way.

Solution 1: This will add 1 to outer boundary but may include result if there's a name that is single 'G', highly unlikely though. WHERE name >= 'A' AND <= CHAR(ASCII('F') + 1)

Solution 2: This solution appends last letter of alphabet field length times. WHERE name >= 'A' AND <= 'FZZZZZZZZZZZZZZZZZZZZZ'

Although the above solutions are workable, my search can be refined as such: A to Fs (should give me everything from A to and including Fs....). With this solution #1 is broken since it works with single ascii.

Suggestions are welcome.

like image 968
ActiveX Avatar asked Mar 27 '12 16:03

ActiveX


People also ask

What is like %% in SQL?

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.

Is between a clause in SQL?

The SQL "between clause," also commonly called a between operator, is what you can use to extract data and compare two pieces of data, two points in time, or two date ranges. For example, you can pull the difference in sales between 2018 and 2019.

Which operator is used to search records for a range?

The SQL Between operator is used to test whether an expression is within a range of values. This operator is inclusive, so it includes the start and end values of the range. The values can be of textual, numeric type, or dates. This operator can be used with SELECT, INSERT, UPDATE, and DELETE command.


2 Answers

You can do:

WHERE name >= 'A' AND name < 'G'
like image 72
Lamak Avatar answered Nov 15 '22 04:11

Lamak


How about this?

WHERE SUBSTR(name, 1, 1) >= 'A' AND SUBSTR(name, 1, 1) <= 'F'
like image 22
alf Avatar answered Nov 15 '22 05:11

alf