Combining multiple 'AND' with 'LIKE' statements in PostgreSQL - sql

Building a basic search tool in PostgreSQL.
When I setup a basic query like below I receive data.
SELECT *
FROM schema_name.table_name
WHERE column_name1 = 'sometext' AND column_name2 LIKE '%sometext%'
;
But when I and more conditions to the where clause like below, the query does execute, but I receive no data.
SELECT *
FROM schema_name.table_name
WHERE column_name1 = 'sometext' AND column_name2 LIKE '%sometext%' AND column_name3 = 'somemoretext'
;
I've tested individual queries to ensure there are records that meet all of the conditions and they exist. However I cannot find a way to tie the criteria together into one query. Most examples I've seen online stop at two conditions or do not combine 'AND' with 'LIKE'. Any help would be appreciated, thanks!
-Edit 1 Begins Here-
Sample Query that generates no data in PostgreSQL
SELECT *
FROM ctgov.studies
WHERE (overall_status = 'Recruiting') AND (official_title LIKE '%immunotherapy%') AND (source LIKE '%university%')
;
When I execute the same search via the website I gather data for the DB it returns 163 matching records. Using 'OR' in this scenario would retrieve records that won't match all the criteria I'm looking for.

I think you need OR instead AND
SELECT *
FROM schema_name.table_name
WHERE column_name1 = 'sometext' OR column_name2 LIKE '%sometext%' OR column_name3 = 'somemoretext'

Thanks for the help everyone, learned that my queries were too strict and I did not account for capitalization in text recognition.

Related

ServiceNow REST API - Querying tables - grouping conditions

I need to query tables in ServiceNow via its REST API while using multiple conditions grouped as following:
( (Condition1 AND Condition2) OR (Condition3 and Condition4) ) AND Condition5 AND Condition6
Does anyone know if this is possible, and if so, how? I've looked into the documentation but I'm not able to understand if it explains how to solve my problem.
Edit 1: I forgot to mention that I did try using parenthesis in my REST calls but it has not worked.
Thanks,
The only way I've figured out how to do it is using the ^NQ (New Query) operator.
In SQL the query would look like this:
WHERE [state] IN (16,17) AND ([assigned_to] = 'value1' OR [assignment_group] IN ('x','y','z'))
So my query looks like this:
sysparm_query=stateIN16,17^assigned_to=value1^NQstateIN16,17^assignment_groupINx,y,z
So you're actually duplicating the common filter (state) and using different filters on each side of the ^NQ.
I guess you could say it would be the equivalent of a UNION in SQL.
SELECT * FROM [wm_task] WHERE [state] IN (16,17) AND [assigned_to] = 'value1'
UNION
SELECT * FROM [wm_task] WHERE [state] IN (16,17) AND [assignment_group] IN ('x','y','z')

Access SQL Query: trouble with * wildcard in WHERE AND LIKE statement

The query I'd like to execute:
SELECT *
FROM qryReportView
WHERE ((ID = 719)
AND (Name Like "*x"));
However when I run this query I get no records returned. Each criterion works on its own:
SELECT *
FROM qryReportView
WHERE ID = 719;
and
SELECT *
FROM qryReportView
WHERE Name Like "*x";
Both queries return records as expected but when I combine them something goes wrong. I know there is at least one record for which both criteria are true.
NOTE: When I replace the * wildcard with an explicit name, I get the correct record returned. This is not a viable solution for me though because my query needs to select records ending in "x" with a number of possible prefixes.
Thank you so much for the help.
Your issue is a logical operator issue.
When you ask an RDBMs for a samich and a coke, if it has a samich but not a coke, you get nothing. Which is what is happening here, you need an 'or'
SELECT *
FROM qryReportView
WHERE (ID = 719
OR
Name Like '*x');

one query for many similar tables

I have an Oracle database with many tables that have identical structure (columns are all the same). The table names are similar also. The names of the tables are like table_1, table_2, table_3...
I know this isn't the most efficient design, but I don't have the option of changing this at this time.
In this case, is it possible to make a single sql query, to extract all rows with the same condition across multiple tables (hundreds of tables) without explicitly using the exact table name?
I realize I could use something like
select * from table_1 UNION select * from table_2 UNION select * from table_3...select * from table_1000
But is there a more elegant sql statement that can be run that extracts from all matching table names into one result without having to name each table explicitly.
Something like
select * from table_%
Is something like that possible? If not, what is the most efficient way to write this query?
You can use dbms_xmlgen to query tables using a pattern, which generates an XML document as a CLOB:
select dbms_xmlgen.getxml('select * from ' || table_name
|| ' where some_col like ''%Test%''') as xml_clob
from user_tables
where table_name like 'TABLE_%';
You said you wanted a condition, so I've included a dummy one, where some_col like '%Test%'.
You can then use XMLTable to extract the values back as relational data, converting the CLOB to XMLType on the way:
select x.*
from (
select xmltype(dbms_xmlgen.getxml('select * from ' || table_name
|| ' where some_col like ''%Test%''')) as xml
from user_tables
where table_name like 'TABLE_%'
) t
cross join xmltable('/ROWSET/ROW'
passing t.xml
columns id number path 'ID',
some_col varchar2(10) path 'SOME_COL'
) x;
SQL Fiddle demo which retrieves one matching row from each of two similar tables. Of course, this assumes your table names follow a useful pattern like table_%, but you suggest they do.
This is the only way I know to do something like this without resorting to PL/SQL (and having searched back a bit, was probably inspired by this answer to count multiple tables). Whether it's efficient (enough) is something you'd need to test with your data.
This is kind of messy and best performed in a middle-tier, but I suppose you could basically loop over the tables and use EXECUTE IMMEDIATE to do it.
Something like:
for t in (select table_name from all_tables where table_name like 'table_%') loop
execute immediate 'select blah from ' || t.table_name;
end loop;
You can write "select * from table_1 and table_2 and tabl_3;"

Compare strings in SQL

I am in a situation where I need to return results if some conditions on the string/character are met.
For example: to return only the names that contain 'F' character from the Person table.
How to create an SQL query based on such conditions? Is there any link to a documentation that explains how can SQL perform such queries?
Thanks in advance
The most basic approach is to use LIKE operator:
-- name starts with 'F'
SELECT * FROM person WHERE name LIKE 'F%'
-- name contains 'F'
SELECT * FROM person WHERE name LIKE '%F%'
(% is a wildcard)
Most RDBMS offer string operations which are able to perform that required task in one way or the other.
In MySQL you might use INSTR:
SELECT *
FROM yourtable
WHERE INSTR(Person, 'F') > 0;
In Oracle, this can be done, too.
In PostgreSQL, you can use STRPOS:
SELECT *
FROM yourtable
WHERE strpos(Person, 'F') > 0;
Usually there are several approaches to solve this, many would choose the LIKE operator. For more details, please refer to the documentation of the RDBMS of your choice.
Update
As requested by the questioner a few words about the LIKE operator, which are used not only in MySQL or Oracle, but in other RDBMS, too.
The use of LIKE will in some cases make your RDBMS try to use an index, it usually does not not try to do so if you use a string functions.
Example:
SELECT *
FROM yourtable
WHERE Person LIKE 'F%';
The query may look like this:
SELECT * FROM Person WHERE FirstName LIKE '%F%' OR LastName LIKE '%F%'

Is there any way to combine IN with LIKE in an SQL statement?

I am trying to find a way, if possible, to use IN and LIKE together. What I want to accomplish is putting a subquery that pulls up a list of data into an IN statement. The problem is the list of data contains wildcards. Is there any way to do this?
Just something I was curious on.
Example of data in the 2 tables
Parent table
ID Office_Code Employee_Name
1 GG234 Tom
2 GG654 Bill
3 PQ123 Chris
Second table
ID Code_Wildcard
1 GG%
2 PQ%
Clarifying note (via third-party)
Since I'm seeing several responses which don't seems to address what Ziltoid asks, I thought I try clarifying what I think he means.
In SQL, "WHERE col IN (1,2,3)" is roughly the equivalent of "WHERE col = 1 OR col = 2 OR col = 3".
He's looking for something which I'll pseudo-code as
WHERE col IN_LIKE ('A%', 'TH%E', '%C')
which would be roughly the equivalent of
WHERE col LIKE 'A%' OR col LIKE 'TH%E' OR col LIKE '%C'
The Regex answers seem to come closest; the rest seem way off the mark.
I'm not sure which database you're using, but with Oracle you could accomplish something equivalent by aliasing your subquery in the FROM clause rather than using it in an IN clause. Using your example:
select p.*
from
(select code_wildcard
from second
where id = 1) s
join parent p
on p.office_code like s.code_wildcard
In MySQL, use REGEXP:
WHERE field1 REGEXP('(value1)|(value2)|(value3)')
Same in Oracle:
WHERE REGEXP_LIKE(field1, '(value1)|(value2)|(value3)')
Do you mean somethign like:
select * FROM table where column IN (
SELECT column from table where column like '%%'
)
Really this should be written like:
SELECT * FROM table where column like '%%'
Using a sub select query is really beneficial when you have to pull records based on a set of logic that you won't want in the main query.
something like:
SELECT * FROM TableA WHERE TableA_IdColumn IN
(
SELECT TableA_IdColumn FROM TableB WHERE TableA_IDColumn like '%%'
)
update to question:
You can't combine an IN statement with a like statement:
You'll have to do three different like statements to search on the various wildcards.
You could use a LIKE statement to obtain a list of IDs and then use that in the IN statement.
But you can't directly combine IN and LIKE.
Perhaps something like this?
SELECT DISTINCT
my_column
FROM
My_Table T
INNER JOIN My_List_Of_Value V ON
T.my_column LIKE '%' + V.search_value + '%'
In this example I've used a table with the values for simplicity, but you could easily change that to a subquery. If you have a large list (like tens of thousands) then performance might be rough.
select *
from parent
where exists( select *
from second
where office_code like trim( code_wildcard ) );
Trim code_wildcard just in case it has trailing blanks.
You could do the Like part in a subquery perhaps?
Select * From TableA Where X in (Select A from TableB where B Like '%123%')
tsql has the contains statement for a full-text-search enabled table.
CONTAINS(Description, '"sea*" OR "bread*"')
If I'm reading the question correctly, we want all Parent rows that have an Office_code that matches any Code_Wildcard in the "Second" table.
In Oracle, at least, this query achieves that:
SELECT *
FROM parent, second
WHERE office_code LIKE code_wildcard;
Am I missing something?