SQL startswith (using `LIKE`) on an expression - sql

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

Related

How to return 0 with where condition user when user search only space character?

Hello I'm using Oracle 11g and i have a data that looks like this
no|name|flag
------------
1|kumar|1
2|rajesh singh|1
3|adi sneedar|1
4|danielle castro|1
5|cef danish|1
if i did
select count(*) from tablename where name like '% %'
it will return 2 records.
if i did "multiple spaces", like 2 or more spaces
select count(*) from tablename where name like '% %'
it returns 0(this means good)
it will return 5 records.
What i want is if the user only input '% %' it will also return 0. But i also wanted that
select count(*) from tablename where name like '%adi sneedar%'
it will return 1
How should i do that in the where condition?
Something like this might suffice, assuming that the '%' are being passed as part of the binding input
select *
from mytable
where name like :bindvar
and replace(replace(:bindvar,'%'),' ') is not null
which basically says they need to enter something that is not solely spaces and percentage signs.

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

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();

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, '%') + '%'

LIKE but NOT LIKE

I have a table filled with company code prefixes (cp-partnum,ag-partnum,ff-partnum). I would like to select all codes which begin with 'cp-partnum' where partnum does not begin with 'I' or 'i'. So 'cp-aaa' is acceptable but 'cp-iaa' is not. How can this be achieved?
edit: to be clear, I would like ONLY the codes that begin with 'cp-[letter where letter is not "I" or "i"]'
You can use SIMILAR TO and a (SQL) regular expression:
yourcolumn SIMILAR TO 'cp-[^iI]%'
If company are always 2 (alpha) characters, you can do something like:
yourcolumn SIMILAR TO '[:ALPHA:]{2}-[^iI]%'
If company code can be any two characters, you can use
yourcolumn SIMILAR TO '__-[^iI]%'
For more complex patterns, study the documentation. SIMILAR TO is available starting with Firebird 2.5.
Use below query:
select *
from companies
where company_code like '__-%'
and company_code not like '__-I%'
and company_code not like '__-i%'
You can use SUBSTRING and NOT IN with only 1 LIKE :
WHERE YourColumn LIKE 'cp-%'
AND SUBSTRING(YourColumn from 4 for 1) NOT IN('i','l')
You can do this:
where col like 'cp-%' and
col not like 'cp-l%' and
col not like 'cp-i%'
For multiple prefixes:
where left(col, 2) in ('cp', 'ag', 'ff') and
substring(col, 4, 1) not in ('l', 'i') and
col like '__-%'
I guess I did not need to support lower case letters so the following worked.
SELECT * FROM product
WHERE product.num LIKE 'CP-%'
AND product.num NOT IN (SELECT product.num FROM product
WHERE product.num LIKE 'CP-I%')

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