A query with a reverse LIKE condition - sql

There is a table with column name "phone" and has different numbers in different formats.
Example:
id | number
1 | 03439879098
2 | 01109890032
3 | +91 932 3233237
Now if I want to search "3233237" then the query will be:
select * from table where number like '%3233237%';
Result will be:
id | number
3 | +91 932 3233237
But in my case I want the reverse
String search = "+92 343 9879098"
select * from table where number like search
The result should be:
id | number
1 | 03439879098
Because the column number and search string has a common string, which is 9879098.
Query should be designed in such a way that it looks for a record that both search string and column value has a common sub string
Kindly give me some idea.

This was a tricky one. You can do it in pure SQL executing:
select * from table where '+92 343 9879098' like '%' || number || '%';
Here we're concatenating the number column with the wildcards %.
*Also You could resolve it programatically:
String search = "+92 343 9879098";
String query = "select * from table where ";
String[] parts = search.split( "\\s+" );
for ( String oneNumber : parts ) {
query += " number like '%" +oneNumber+ "%' OR";
}
query += " false"; // this, or trim the last OR calculating the string length
Cheers.

Have you tried NOT LIKE so it'd be something like
select * from table where name not like search

Related

SQL subquery result in WHERE

I have a Paths table with columns PathID (unique) and PathStr.
I'd like to get all PathStr records in this table what starts with a string, came from a selected PathID.
In other words I'd like to get all subfolders of a folder if I know the PathID of the root folder.
Example table:
PathID | PathStr
-------+------------------------
1 | D:\Project1
2 | D:\Project1\Sub1
3 | D:\Project1\Sub1\Sub11
4 | D:\Project2
5 | D:\Project2\Sub1
Required result if the PathID = 1:
D:\Project1
D:\Project1\Sub1
D:\Project1\Sub1\Sub11
My query looks like this now, but I'm stuck with the subquery at WHERE:
SELECT P.PathStr As 'Folder'
FROM Paths AS P
WHERE P.PathStr LIKE (SELECT Paths.PathStr FROM Paths WHERE Paths.PathID = 1) + "%"
I guess I can't simply concatenate the result of the sub-query with a string, but I don't know how can I do that, I didn't find solution with my friend google :)
The result of the sub-query is always one record.
Thank you
I would suggest instead using exists:
SELECT p.PathStr as Folder
FROM Paths p
WHERE EXISTS (SELECT 1
FROM Paths p2
WHERE p2.PathId = 1 AND
p.PathStr LIKE CONCAT(p2.PathStr, '%')
);
You have not tagged your database. The standard operator for string concatenation is || and many databases also support a CONCAT() function. The use of + for string concatenation is quite limited.
EDIT:
To fix the problem mentioned in the comment:
SELECT p.PathStr as Folder
FROM Paths p
WHERE EXISTS (SELECT 1
FROM Paths p2
WHERE p2.PathId = 1 AND
CONCAT(p.PathStr, '\') LIKE CONCAT(p2.PathStr, '\%')
);
Note: In some databases the backslash would need to be doubled so it is not an escape character.

How can I gather a sqldatasource's results as a comma separated string in code behind?

Hello and thank you for your time. If I have a Sqldatasource that is pulling from my database a list of ID's based on a certain criteria, how can I call that list formatted to a comma separated string in code behind? For example, say this is the query I'm using:
SELECT ID FROM MyDatabase WHERE Email <> ''
Results being:
| ID |
------
| 16 |
| 2 |
| 81 |
| 4 |
How can I call call that in code behind as a comma separated list with no trailing comma like below?
16,2,81,4
Try this (For in code behind):
Fill the data in datatable and access each data using for loop and concat string.
For iRowIdx = 0 To dtblData.Rows.Count - 1
Result += dtblData.Rows(iRowIdx)("ID") + ','
Next
Instead you can combine the values in SQL:
SELECT
STUFF(
(SELECT ',' + CAST(ID as varchar(max))
FROM (SELECT ID
FROM MyDatabase) AS B FOR
XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 1, '')
AS ExpectedResult
One thing that you can do is to use a Datareader. This will allow you to cycle through the records being returned from the query and access all of the values in the code behind.
You can use it like this,
command = new sqlcommand("Select ID from [Test]", conn)
datareader = command.ExecuteReader()
While datareader.Read()
'Access the Columns here
End While

querying WHERE condition to character length?

I have a database with a large number of words but i want to select only those records where the character length is equal to a given number (in example case 3):
$query = ("SELECT * FROM $db WHERE conditions AND length = 3");
But this does not work... can someone show me the correct query?
Sorry, I wasn't sure which SQL platform you're talking about:
In MySQL:
$query = ("SELECT * FROM $db WHERE conditions AND LENGTH(col_name) = 3");
in MSSQL
$query = ("SELECT * FROM $db WHERE conditions AND LEN(col_name) = 3");
The LENGTH() (MySQL) or LEN() (MSSQL) function will return the length of a string in a column that you can use as a condition in your WHERE clause.
Edit
I know this is really old but thought I'd expand my answer because, as Paulo Bueno rightly pointed out, you're most likely wanting the number of characters as opposed to the number of bytes. Thanks Paulo.
So, for MySQL there's the CHAR_LENGTH(). The following example highlights the difference between LENGTH() an CHAR_LENGTH():
CREATE TABLE words (
word VARCHAR(100)
) ENGINE INNODB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;
INSERT INTO words(word) VALUES('快樂'), ('happy'), ('hayır');
SELECT word, LENGTH(word) as num_bytes, CHAR_LENGTH(word) AS num_characters FROM words;
+--------+-----------+----------------+
| word | num_bytes | num_characters |
+--------+-----------+----------------+
| 快樂 | 6 | 2 |
| happy | 5 | 5 |
| hayır | 6 | 5 |
+--------+-----------+----------------+
Be careful if you're dealing with multi-byte characters.
I think you want this:
select *
from dbo.table
where DATALENGTH(column_name) = 3
SELECT *
FROM my_table
WHERE substr(my_field,1,5) = "abcde";

SQL select query with wildcard on input parameter

Same question as my other thread basically!
I have a db table and I need to write a query that will return results based on a partial match of a string.
Example:
DB field: abc
Search term: 123abc
i.e. I want given 123abc for it to return the row that has the abc field in it!
My attempt:
SELECT mood from users where '$searchTerm' like '%' || dbField
Is something like that possible in any way?
Well basically I'm trying to match the numbers with the search term la77740985
id | mood | numberfield
==== ===== ============
1 bad '77740985'
2 good '77513755'
Running the query returns both rows!
Note: The wildcard should only be in the beginning of the string in other words I want the search term to begin with anything but still match the string from the database that basically have the same ending.
It worked like this:
SELECT mood from users where '$searchTerm' like concat('%',numberField);
SELECT mood
from users
where '$searchTerm' like '%' || numberField
This will match $searchTerm = '123abc' against dbField that contains 'abc'. It's correct. If you need contains (anywhere), then add || '%' at the end.
Full test script
drop table if exists users2;
create table users2 (mood, numberfield);
insert into users2(mood,numberfield) values ('happy','77740985');
insert into users2(mood,numberfield) values ('sad','77513755');
Then run this
SELECT mood from users2 where 'la77740985' like ('%' || numberfield);
Output
mood
=======
'happy'

SQL update statement to change the value of a field and not replace it

I'm in the process of migrating some databases. I have this table that has a couple of hundred rows, and has a filename column. To each record in this table, the filename column needs to be altered and part of a path needs to be prepended to the value that is in that field.
The table is like:
| 1 | filename1 |
| 2 | filename2 |
and needs to become:
| 1 | path/filename1 |
| 2 | path/filename2 |
I am not an SQL guru, but I know the basics. This eludes me though. Is there a way to do something like:
update table
set filename = 'path/' + filename
where id = 1;
You pretty much have it right there. You don't need to specify a where clause if you want to do it for all the rows, so then it would just be:
update table set filename = 'path/' || filename;
(|| is the concatenation operator in PostgreSQL)
They have told you how to write teh concatenation, I suggest you run this selct first to see waht your results will be:
select filename, 'path/'|| filename from table
where id = 1;
I think this should work:
UPDATE table SET filename = CONCAT("path/", filename);
UPDATE table
SET filename = 'path/' || filename
WHERE id = 1