SQL For Programmers – Finding a String


tp_vol3_025 Many times in our queries, we aren’t looking for an exact match.  We are looking for one string that exists in another.  There are a couple statements available to us that will allow us to do this.

The first of these is the LIKE statement, and if you are familiar with DOS or the Linux equivalent, this should look familiar to you.

The most common usage of LIKE looks like this:

SELECT * FROM someTable
WHERE fieldName LIKE '%stringHere%'

Note the % inside the single quote marks.

This statement is telling SQL to find all of the rows from someTable where the contents of fieldName has the string ’stringHere’ in it.

You could also do something like:

SELECT * FROM someTable
WHERE fieldName LIKE 'stringHere%'

which would find all the rows where fieldName started with ’stringHere’

You can also use the following pattern matching characters:

Symbol Descriptions
_ Look for any single character
[] Look for any single character listed in the set
fieldName LIKE ‘[abc]%’
Looks for anything that starts with a, b, or c.
[^] Look for any single character not listed in the set
fieldName LIKE ‘[^abc]%’
Looks for anything that doesn’t start with a, b or c.

If you need to find a string that includes one of these symbols, you’ll need to ESCAPE it and you’ll need to define the escape sequence.

So to look for a % in the middle of the string you would use:

SELECT * FROM someTable
WHERE fieldName LIKE '%%stringHere%'
ESCAPE '%'

This will look for all rows where the fieldName starts with the string ‘%stringHere’ because we’ve told it that % is the escape character and we’ve used %% twice in our search string.

A few other posts about SQL that might help you:


LIKE (Matching to a Pattern), Part 3 of 3

SQL Tutorial

Ads by Lake Quincy Media

Other Related Items:

Wilson Jones 362 Line Basic Round Ring View Binder, 3-Inch Capacity, 8.5 x 11 Inch Sheet Size, White (W362-49W)Wilson Jones 362 Line Basic Round Ring View Binder, 3-Inch Capacity, 8.5 x 11 Inch Sheet Size, White (W362-49W)Looks good on the shelf or on the go. Customize for filing or presentations with a non-glare overlay on the spine and front and back covers. Use the round ring open and close triggers for easy access. Take advantage of interior pockets for extra storage.
SQL SVR 2008 STD FOR SMALL BUS 1PK DSP OEI DVD 5 CLT KITSQL SVR 2008 STD FOR SMALL BUS 1PK DSP OEI DVD 5 CLT KITMicrosoft SQL Server 2008 Standard Edition for Small Business Database Reporting - License and Media - OEM - 5 CAL - PC
In case of parallel litigation where parties' contract contained clause designating Australian court as proper forum, Federal Court of Australia rules ... An article from: International Law UpdateThis digital document is an article from International Law Update, published by Transnational Law Associates on January 1, 2008. The length of the art... Read More >

Related Post

Comments are closed.

DotNetNuke Sponsor

 

Most Valuable Blogger
Sponsor