How to fetch a range of numbers using like operator - sql

Currently I'm trying to fetch the records which are matching my condition.
I'm using wildcard operator but it's not fetching the records as I expect.
I have multiple records in my table and I'm using the query below:
select *
from My_table
where RegNum like '117[15-24]%'
I thought above query will fetch the records from 11715 to 11724, but currently it's fetching records from 11710 to 11719. I got to know that % wildcard operator will consider single digits only.
Is there any other way to use two digit number in wildcard operator or is there any other solution to fetch the records what I'm looking for?

I speculate that you are using SQL Server. When comparing numerical ranges, the best thing to do is to just use an inequality. If your RegNum column is text, then cast it to integer first and then compare:
SELECT *
FROM My_table
WHERE (CAST RegNum AS int) BETWEEN 11715 AND 11724;
If you want to use LIKE, we might be able to try:
SELECT *
FROM My_table
WHERE RegNum LIKE '1171[5-9]' OR RegNum LIKE '1172[0-4]';

The logic you want is perhaps better captured by:
where left(regnum, 5) between '11715' and '11724'
Not all databases support left(), in those, use the substring function instead.
You have a logic fallacy in wanting to use like for numeric ranges. like is for strings. If you want numeric ranges, use numbers. You could do this with the above condition:
where cast(left(regnum, 5) as int) between 11715 and 11724
But this is logically equivalent to the original string comparison.

Related

How to Extract only numbers from the String without using function in SQL

Table contains data as below
Table Name is REGISTER
Column Name is EXAM_CODE
Values like ('S6TJ','S7','S26','S24')
I want answer like below
Result set - > (6,7,26,24)
Please suggest solution - since regexp_replace is not recognized built in function name in SQL.
The complexity of the answer depends on two things: the RDBMS used and whether the numbers in the EXAM_CODE are contiguous.
I have assumed that the RDBMS is SQL Server and the numbers in EXAM_CODE are always contiguous. If not, please advise and I can revise the answer.
The following SQL shows a way of accomplishing the above using PATINDEX.:
CREATE TABLE #REGISTER (EXAM_CODE VARCHAR(10));
INSERT INTO #REGISTER VALUES ('S6TJ'),('S7'),('S26'),('S24');
SELECT LEFT(EXAM_CODE, PATINDEX('%[^0-9]%', EXAM_CODE) - 1)
FROM (
SELECT RIGHT(EXAM_CODE, LEN(EXAM_CODE) - PATINDEX('%[0-9]%', EXAM_CODE) + 1) + 'A' AS EXAM_CODE
FROM #REGISTER
) a
DROP TABLE #REGISTER
This outputs:
6
7
26
24
PATINDEX matches a specified pattern against a string (or returns 0 if there is no match).
Using this, the inner query fetches all of the string AFTER the first occurence of a number. The outer query then strips any text that may appear on the end of the string.
Note: The character A is appended to the result of the inner query in order to ensure that the PATINDEX check in the outer query will make a match. Otherwise, PATINDEX would return 0 and an error would occur.

Get records matching regex in Ms-Sql

I am using query as follows to get any records that begins with any character, has bunch of 0s and ends with number (1 in this case).
where column like '_%[0]1'
But the issue is it's even returning me d0101 etc. which I don't want. I just want d0001, or r0001. Can I use it to exactly match pattern, not partially using like?
Any other options in ms-sql?
SQL-Server does not really do proper regular expressions but you can generate the search clause you want like this:
where column like '_%1' and column not like '_%[^0]%1'
The second condition will exclude all cases where you have a character other than 0 in the middle of the string.
It will allow strings of all possible lengths, provided they start with an arbitrary character, then have any number of 0s and finish with a 1. All other strings will not satisfy the where clause.
create table tst(t varchar(10));
insert into tst values('d0101');
insert into tst values('d0001');
insert into tst values('r0001');
select * from tst where PATINDEX('%00%1', t)>0
or
select * from tst where t like '%00%1'
You use the _ to say that you don't care what char is there (single char) and then use the rest of the string you want:
DECLARE # TABLE (val VARCHAR(100))
INSERT INTO #
VALUES
('d0001'),
('f0001'),
('e0005'),
('e0001')
SELECT *
FROM #
WHERE val LIKE '_0001'
This code only really handles your two simple examples. If it is more complex, add it to your post.

SQL Query to pull rows starting with a certain 3 digits

I have a numbers column in my sql table and I want to pull all the numbers that start with 3 specific digits; how would I query this?
Use the "LIKE" query:
123 is the prefix. I think you have to store the numbers as strings though, just try it out on your data set :-)
SELECT * from TableName Where ColumnName LIKE '123%'
See also this Q&A: In MySql, find strings with a given prefix

PostgreSQL: return row where any column value like variable

I am trying to have the user search for a value in a SQL table, and the user is returned with any row that contains that value. At the moment, I can make it work such that the code is:
SELECT * FROM table WHERE lower('foo') in (lower('col1'),lower('col2'),etc)
However, I would like it to be able to search every column and return any row LIKE 'foo'. For instance,
SELECT * FROM table WHERE (lower('col1'), lower('col2'), etc) like lower('%foo%')
But that doesn't work.
Any suggestions?
I believe you need to use multiple WHERE clauses instead of grouping them all into one statement. Try this:
SELECT * FROM table
WHERE lower(col1) like lower('%foo%')
OR lower(col2) like lower('%foo%')
OR etc like lower('%foo%')
You can convert the whole row to a string and then use LIKE on the result of that:
select *
from the_table
where lower(the_table::text) like '%foo%';
the_table::text returns all columns of each row as a comma separated list enclosed with parentheses, e.g. (42,Arthur,Dent). So the above is not 100 identical to a LIKE condition applied on each column - but probably does what you want.

SQL - just view the description for explanation

I would like to ask if it is possible to do this:
For example the search string is '009' -> (consider the digits as string)
is it possible to have a query that will return any occurrences of this on the database not considering the order.
for this example it will return
'009'
'090'
'900'
given these exists on the database. thanks!!!!
Use the Like operator.
For Example :-
SELECT Marks FROM Report WHERE Marks LIKE '%009%' OR '%090%' OR '%900%'
Split the string into individual characters, select all rows containing the first character and put them in a temporary table, then select all rows from the temporary table that contain the second character and put these in a temporary table, then select all rows from that temporary table that contain the third character.
Of course, there are probably many ways to optimize this, but I see no reason why it would not be possible to make a query like that work.
It can not be achieved in a straight forward way as there is no sort() function for a particular value like there is lower(), upper() functions.
But there is some workarounds like -
Suppose you are running query for COL A, maintain another column SORTED_A where from application level you keep the sorted value of COL A
Then when you execute query - sort the searchToken and run select query with matching sorted searchToken with the SORTED_A column