Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL Query needed if search criteria is longer than column value

I have a following sample table structure

Name Address
Name1 Address1
Name2 Address2

I need to get the Name1 but my search criteria is longer than the column value.

Sample query

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT * 
FROM SampleTable 
WHERE Name = 'Name1Me'

I have tried truncating the search criteria until I get a match like below

SELECT * 
FROM SampleTable 
WHERE Name = 'Name1Me'

if no result then

SELECT * 
FROM SampleTable 
WHERE Name = 'Name1M'

if no result then

SELECT * 
FROM SampleTable 
WHERE Name = 'Name1M'

Result okay

But this will make a lot of queries if the search criteria is much longer than the column value.

I’m asking if there’s a better query for situations like this.

Edit:
I’m using MariaDB 10.3 on a Raspberry Pi 3B+.

By better, I mean if there’s a single query for this or if it’s possible to do this in less queries.

>Solution :

You can use something like this – reducing the right operand to the length of the left operand:

SELECT * 
FROM SampleTable 
WHERE Name = left('Name1Me',char_length(Name))

But beware:

  1. The actual string functions to use may change depending on the database vendor (you have not tagged), and/or if you use some international character sets.
  2. You need to make sure that the length of the search criteria and the length of the column value do not result in invalid function calls (zero length strings, for example).
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading