Creating an SQL query that selects a specific entry in a table - sql

I have a table called grades that has 4 columns: ID, math, science and history.
I want to create an sql query that selects from the table "grades" the specific entry where "ID" is equal to a variable. This variable changes every time the program is run. What I have tried so far but is not working is this:
"SELECT * FROM grades Where ID LIKE %" + IDString + "%"
"SELECT * FROM grades Where ID LIKE %IDString%"
"SELECT * FROM grades Where ID LIKE 'IDString'"
Note: IDString is the String variable.
Note: I am using Java and Sqlite.
String IDString = "12345";
ResultSet rs = connection.createStatement().executeQuery("SELECT * FROM grades Where ID LIKE '%' || IDString || '%' ");
this code is to make my problem a little more clear.

Use concat function to concat the variable and strings.
SELECT * FROM mytable Where col2 LIKE CONCAT('%', #start, '%')
or in your case:
SELECT * FROM grades Where ID LIKE CONCAT('%', #IDString, '%')
Here is a small demo
In SQLite this would look like this:
SELECT * FROM grades Where ID LIKE '%' || #IDString || '%'
But in SQLite you can not use variables. This needs to be done in your Java part of the code.
When sending the query from JAVA you can do it like this:
"SELECT * FROM grades Where ID LIKE '%' ||" + IDString + "|| '%' "

Your own examples are wrong because the pattern literal should be enclosed into single quotes. The pattern characters like % or _ will be inside the literal:
SELECT * FROM grades Where ID LIKE '%IDString%'
If you'd like to substitute a value in the "pure MySQL", put the pattern characters into the variable, but not into query body:
SET #pattern = CONCAT('%', #var, '%');
SELECT * FROM grades WHERE ID LIKE #pattern;
https://www.db-fiddle.com/f/vr13gVV19CTcR1kbgohS34/0
The same for PHP or other "external" languages. You can use prepared statement with a value which already contains pattern characters. Something like that:
$sth = $dbh->prepare("SELECT * FROM grades WHERE ID LIKE ?");
$sth->execute('%' . $var . '%'));
$result = $sth->fetchAll();

Related

SQL Server check if value is substring inside isnull

I have a field in UI interface that passes to a stored procedure a null value (when field is unfilled) or a contract number when it is filled. Substrings of the contract number are accepted as input.
Inside the procedure, I need to filter the results by this parameter.
I need something similar to this:
SELECT * FROM tableName tn
WHERE
tn.ContractNumber LIKE ISNULL('%' + #contractNumber + '%', tn.ContractNumber)
What do you think it is the best approach? Problem is that using a condition like this does not return values.
Simply:
SELECT *
FROM tableName tn
WHERE tn.ContractNumber LIKE '%' + #contractNumber + '%'
OR #contractNumber IS NULL
You are really checking multiple condition, so having them separated reads more intuitive (for most people, anyway).
I assume this is just a sample query, and you are not selecting * in reality...
Another one:
SELECT *
FROM tableName tn
WHERE tn.ContractNumber LIKE '%' + ISNULL(#contractNumber, '%') + '%'

sql, using a subquery in the like operator

why does this work,
select*
from some_table
WHERE some_column_name like '%i%'
and not this?
select*
from some_table
WHERE
some_column_name like (select ''''+'%' +value +'%' + '''' as val
from [dbo].[fn_Split](' i this is a test testing Chinese undefined',' ')
where idx = 0)
I am trying to search for individual words instead of the whole phrase, the split function above will split the string on space characters and plug the results into a table with two columns, idx and value.
the LIKE operator takes a string for an argument. It cannot be used on a table, which I assume your function returns.
I think what you want to do is JOIN to the function, and then check where LIKE fn.Value:
select *
from some_table t
INNER JOIN (select value as val
from [dbo].[fn_Split](' i this is a test testing Chinese undefined',' ')
where idx = 0) f
ON t.some_column_name like '%'+f.val+'%'
If your subquery is guaranteed to only return one result, you could try putting the modulo symbols around it instead of inside it:
LIKE '%' + (YourSubQuery) + '%'
One possible reason is because you are appending single quotes onto the beginning and end of the string, and none of the values actually store single quotes in the string.
Another reason is might not work is because the subquery returns more than one row or zero rows. The function fn_split() is your own function, so I don't know what it returns. You have a subquery in a context where it can return at most one row and one column. That is called a scalar subquery. If the subquery returns more than one row, you will get an error. If the subquery returns no rows -- for instance, if idx starts counting at 1 rather than 0 -- then it will return NULL which fails the test.
If you want to find a match this way, I would recommend exists:
select t.*
from some_table t
where exists (select 1 as val
from [dbo].[fn_Split](' i this is a test testing Chinese undefined',' ') s
where s.idx = 0 and
t.some_column_name like '%' + value + '%'
);
The results of your sub-query is a literal string. The % symbol isn't seen as a wildcard. Also, does your functions return multiple rows? If so, LIKE operator can only evaluate a single value.
If your functions does return a single value, I would suggest looking into using Dynamic SQL. Something like the following:
DECLARE #SQL VARCHAR(MAX), #WildCard VARCHAR(MAX)
SELECT #WildCard = '%' + value + '%'
FROM [dbo].[fn_Split](' i this is a test testing Chinese undefined',' ')
WHERE idx = 0
SET #SQL = 'SELECT * FROM some_table WHERE some_column_name like ''' + #WildCardWildCard + ''''
EXEC(#SQL)

SQLite: order so that results with same starting letter would come first?

SQLite 3.7.11
Given I have these two records in a SQLITE table, with the field called name:
"preview"
"view"
If I run the query:
SELECT * FROM table WHERE name LIKE "%" + $keyword + "%" ORDER BY name
with $keyword set to "vi"
I would get the results in this order:
1) "preview"
2) "view"
Is there a way to order so that the names whose first letter is the same as the first letter of the keyword (in this example "v") would come first?
You can sort by the position of your keyword in the search string
SELECT * FROM your_table
WHERE name LIKE concat('%', '$keyword', '%')
ORDER BY POSITION('$keyword' IN name)
name
Not sure if it can be done less verbose, but this should work. I used ? as a placeholder for your variable. The query as you posted it doesn't seem to be correct SQL.
SELECT * FROM table1
WHERE name LIKE '%' || ? || '%'
ORDER BY (CASE WHEN SUBSTR(Name,1,1) = SUBSTR(?,1,1) THEN 0 ELSE 1 END),
name

Using strings from one column to search inside a string in another SQL

I am trying to search inside a sentence using the string from another column in SQL. I have a large list of keywords and their rating on a scale from 1 to 6. I am trying to search through data pulled down from Twitter to see what people thought of certain movies (i.e. Wreck It Ralph) and give the movie an aggregate score. The problem I am having is that the data pulled from Twitter isn't broken up, but still in a full sentence. I can't figure out a way to search through the sentence for the keyword. Here is a query that works:
SELECT SUM(K.Score)
FROM wreck_it_ralph WIR, Keyword K
WHERE t_text LIKE '%fantastic%'
AND K.word = 'fantastic';
Here is a query I tried using concatenation, but was unsuccessful:
SELECT SUM(K.Score)
FROM Wreck_it_Ralph WIR, Keyword k
WHERE t_text LIKE ('%' + k.word + '%');
Different databases have different ways of concatenating strings. In Oracle or Postgres, try this:
SELECT SUM(K.Score)
FROM Wreck_it_Ralph WIR, Keyword k
WHERE t_text LIKE '%' || k.word || '%'
In SQL Server or Sybase:
SELECT SUM(K.Score)
FROM Wreck_it_Ralph WIR, Keyword k
WHERE t_text LIKE '%' + k.word + '%'
And in MySQL:
SELECT SUM(K.Score)
FROM Wreck_it_Ralph WIR, Keyword k
WHERE t_text LIKE concat('%', k.word, '%')
Do note that you have a problem with partial word matches. So, something "dislike" will match "like". You may want to look into the full text capabilities of whichever database you are using, because that takes into account punctuation, full words, and stop-lists.
MSSQL-:
SELECT SUM(K.Score)
FROM Wreck_it_Ralph WIR, Keyword k
WHERE t_text LIKE '%' + k.word + '%';

SQL startswith (using `LIKE`) on an expression

What's an appropriate way to do startswith(expression) in SQL?
I can do it with LIKE ((expression) || '%'), but it doesn't look very nice to me.
Full query is in form:
SELECT …, (SELECT COUNT(*)
FROM post AS child
WHERE child.path LIKE (post.path || '%')
AND child.depth >= post.depth)
FROM post WHERE …
I suppose it is preferable to use LIKE because of DB indexing for this case.
Just use LIKE 'input%'. I.E:
WHERE child.path LIKE post.path + '%'
(I assume this is for SQL Server, though this syntax probably works elsewhere)
In standard SQL, you can also say:
where position(post.path in child.path) = 1
I don't know if your RDBMS supports that. PostgreSQL does.
You can use
where DATE LIKE '[(SELECT STR(YEAR(GETDATE())-1))]%'
WHERE child.path LIKE '[(SELECT STR(YEAR(GETDATE())-1))]%' (post.path || '%')
WHERE CustomerName LIKE 'a%'
--Finds any values that start with "a"
WHERE CustomerName LIKE '%a'
--Finds any values that end with "a"
WHERE CustomerName LIKE '%or%'
--Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%'
--Finds any values that have "r" in the second position
WHERE CustomerName LIKE 'a__%'
--Finds any values that start with "a" and are at least 3 characters in length
WHERE ContactName LIKE 'a%o'
--Finds any values that start with "a" and ends with "o"
-- Case insensitive
2
SELECT * FROM my_table WHERE upper(my_column) LIKE 'SEARCHED %';
-- starts with
3
SELECT * FROM my_table WHERE upper(my_column) LIKE '% SEARCHED';
-- ends with
4
SELECT * FROM my_table WHERE upper(my_column) LIKE '%SEARCHED%'; -- contains