Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to check if any case of a pattern exist in a column using SQL

I am trying to write code that allows me to check if there are any cases of a particular pattern inside a table.

The way I am currently doing is with something like

select count(*) 
from database.table 
where column like (some pattern)

and seeing if the count is greater than 0.

I am curious to see if there is any way I can speed up this process as this type of pattern finding happens in a loop in my query and all I need to know is if there is even one such case rather than the total number of cases.

Any suggestions will be appreciated.

EDIT: I am running this inside a Teradata stored procedure for the purpose of data quality validation.

like image 990
Hangil Jang Avatar asked Oct 29 '15 04:10

Hangil Jang


People also ask

How do I find a specific pattern in a column in SQL?

LIKE clause is used to perform the pattern matching task in SQL. A WHERE clause is generally preceded by a LIKE clause in an SQL query. LIKE clause searches for a match between the patterns in a query with the pattern in the values present in an SQL table.

What is the command to check patterns in SQL?

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

How do you find patterns in data and apply it for testing in SQL?

SQL pattern matching allows you to search for patterns in data if you don't know the exact word or phrase you are seeking. This kind of SQL query uses wildcard characters to match a pattern, rather than specifying it exactly. For example, you can use the wildcard "C%" to match any string beginning with a capital C.


2 Answers

Using EXISTS will be faster if you don't actually need to know how many matches there are. Something like this would work:

IF EXISTS (
    SELECT *
    FROM bigTbl
    WHERE label LIKE '%test%'
)
    SELECT 'match'
ELSE
    SELECT 'no match'

This is faster because once it finds a single match it can return a result.

like image 168
Mike D. Avatar answered Sep 22 '22 13:09

Mike D.


If you don't need the actual count, the most efficient way in Teradata will use EXISTS:

select 1
where exists 
 ( select *
   from database.table 
   where column like (some pattern)
 )

This will return an empty result set if the pattern doesn't exist.

like image 42
dnoeth Avatar answered Sep 24 '22 13:09

dnoeth