2

How am I going to use BETWEEN Operator with Text Value or what is the right syntax when you will select all products with a ProductName for example ending with any of the letter BETWEEN 'C' and 'M'?

3
  • 1
    Please tag your question with the database you are using. Commented Jun 30, 2015 at 12:25
  • 1
    If this is going to be a common query, it may be worth investigating whether your database system (e.g. SQL Server, mysql, Oracle, etc) has features that would make an index possible for this query - e.g. function-based indexes or indexed computed columns. To know that, though, we'd need to know which system you're using. Commented Jun 30, 2015 at 12:35
  • I'm trying to code it on w3schools code generator Commented Jun 30, 2015 at 12:37

2 Answers 2

5

Most SQL dialects provide the RIGHT() function. This allows you to do:

WHERE RIGHT(TextValue, 1) BETWEEN 'C' AND 'M'

If your database doesn't have this function, you can do something similar with the built-in functions. Also, the exact comparison might depend on the collation of the column/table/database/server. Sometimes comparisons are independent of case and sometimes they are dependent on case.

Sign up to request clarification or add additional context in comments.

4 Comments

Why there's an error occured when I ran it on w3sschools?
Seems like it's correct but it's not running on w3Schools.
Seems like the w3sschools dbms doesn't support the RIGHT function.
@user3783598 . . . It looks like they are running Oracle on the backend. The equivalent in Oracle is: substr(customername, length(customername), 1).
1

In case you are interested in an alternative method (which does work with the w3schools SQL editor), you can also use the LIKE operator:

WHERE ProductName LIKE '%[c-m]'

This will get you all Product Names ending on any character between C and M. (It does work with the w3schools SQL Editor.)

In this case, the LIKE operator is using two wildcard characters:

1.%

Any string of zero or more characters.

2.[c-m]

Any single character within the specified range ([a-f]) or set ([abcdef]).

You can find more information about the LIKE operator here: https://msdn.microsoft.com/en-us/library/ms179859.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.