Learn SQL LIKE Pattern Matching Tutorial

Page 1

Learn

Pattern Matching Tutorial

ThisPost/Pagemaycontainaffiliate links,meaningwhenyouclickthelinks andmakeapurchase,wereceivea commission.

TheSQLLIKEOperatorforPatternMatching

Likeitornot,the LIKE operatorisessentialinSQL.Itgivesdatapractitionersthepowertofilter dataonspecificstringmatches.Thisarticleprovidesaquicktutorialon LIKE forbeginnersand intermediates.Ifyoulearnbetterwithhands-onpractice,youcanalsofollowalong(andrunthe code)onthisDataCampWorkspace

Learn SQL Commands —25 Most Popular SQL Commands

Learn SQL Commands 25 Most Popular SQL Commands

Learn the basics of the 25 most popular SQL commands and how to use them What is SQL? SQL

Learn Power BI Calculate function Tutorial

Learn Power BI Calculate function Tutorial Learn how to use the Power BI CALCULATE function while giving examples of how you can use it The

SQL Joins Cheat Sheet

SQL Joins Cheat Sheet

With this SQL Joins cheat sheet, you'll have a handy reference guide to joining data in SQL SQL, also known as St

21 Essential Tools for Python

21 Essential Tools for Python Learn about the essential Python tools for software development, web scraping and development, data analysis a

Creating Synthetic Data with Python Faker Tutorial Creating Synthetic Data with Python Faker Tutorial Generating synthetic data using Python Faker to supplement real world data for applicatio

What is R? The Statistical Computing base for data science

What is R? The Statistical Computing base for data science Learn the history of R programming language and discover why it is the most wid

Certied CyberOps

CBROPS 200

/1 /2 , :5://a .b .c /2 /0 9/l -s -l -p -m -t .h / HOME AskCarlito blogspot com | Home | About | Contact      FEATURES Home / Unlabelled / Learn SQL LIKE Pattern Matching Tutorial  ketan Raval  24 days ago UseLIKEtofilterSQLrecordsonspecificstringmatches Thistutorialteachesyouto usewildcards,NOT,LOWER,UPPER,andCASEWHENwithLIKE.
SQL LIKE
Learn SQL LIKE Pattern Matching Tutorial
DI SCLOSURE
Cisco
Associate
201 Q&A and more POPULAR POST S

employees

emp_no birth_d ate first_na me last_na me gender hire_dat e

10001

19530902T00:0 0:00.000 Z

Georgi Facello M

19860626T00:0 0:00.000 Z

10002

19640602T00:0 0:00.000 Z

Bezalel Simmel F

1985-1121T00:0 0:00.000 Z

10003

19591203T00:0 0:00.000 Z

Parto Bamford M

19860828T00:0 0:00.000 Z

Supposeyouhavean employees tableandwouldliketofindallnamesthatstartwith ‘A’ .You couldspendtimelookingthroughthetablemanually.Butwhywouldyoudothatwhenyouhave theLIKEoperator?

Code

SELECTDISTINCT first_name FROMemployees WHEREfirst_nameLIKE'A%'

Themagichereisintheclause `WHERE first_name LIKE ‘A%’` ,whichmeans“find all first_name startingwithAandendingwithanynumberofcharacters.”The `A%` hereis knownasapatternformatching.

The `%` isnottheonlywildcardyoucanuseinconjunctionwiththe LIKE operator.Youcould usetheunderscoresign `_` too.

 `%` matchesanynumberofcharacters.

 `_` matchesanysinglecharacter

/1 /2 , :5://a .b .c /2 /0 9/l -s -l -p -m -t .h /
POWERED BY DATACAMP WORKSPACE COPY CODE Cisco Certied CyberOps Associate CBROPS 200 201 Threat Hunting and Defending using Cisco Technologies for CyberOps CBROPS 200 201 Th
Learn Piano very Easy way
BE A PI ANO PRO
Home earning with social media EARN MONEY FROM SOCI AL
MEDI A
A
millionaire's Secret
J OHN CRESTANI
T HI S SECRET FRUI T RAPI DLY MELT S FAT

Youcanuse LIKE toachieveavarietyofpattern-matching.Here’show

BeginnerSQLLIKEExamples

Below,we’veoutlinedsomepracticalexamplesofhowyoucanusethe LIKE statementandthe resultsfromoursampledataset.

1.Use LIKE forExactStringMatch

Ifyou’dliketoperformanexactstringmatch,useLIKEwithout ‘%’ or ‘_’

Code SELECT

first_name,last_name FROMemployees

WHEREfirst_nameLIKE'Barry'--thesameasWHEREfirst_name=‘Barry’

2.Use ‘%’ tomatchanynumberofcharacters

‘%’ canbeusedtomatchany(evenzero)numberofcharacters–anumber,analphabet,ora symbol.

Supposeyouwanttofindallemployeeswhosenamestartswith ‘Adam’ ;youcanusethe pattern ‘Adam%’

SELECTDISTINCT first_name FROMemployees

first_nameLIKE'Adam%'

Tofindnamesthatendwith ’Z’ ,trythepattern ‘%z’ .Youcanalsousemultiple ‘%’ inone pattern.Forexample,ifyouwanttofindnamesthatcontainz,use ‘%z%’

Like

game

the

onlyfitonecharacter

/1 /2 , :5://a .b .c /2 /0 9/l -s -l -p -m -t .h / Thesyntaxiseasytoremember.Itissimply
the
Hangman,
underscoresign can
Code column_nameLIKEpattern POWERED BY DATACAMP WORKSPACE COPY CODE
POWERED BY DATACAMP WORKSPACE COPY CODE
Code
WHERE
POWERED BY DATACAMP WORKSPACE COPY CODE 3.Use ‘_’ tomatchone(andonlyone)character There is a secret ingredient in that that makes people thin no matter what they eat? Social media jobs are really hot right now !! GET PAI D ON SOCI AL MEDI A September (24) BLOG ARCHI VE ▼ 2022 (129) ▼ September (24) Data Science Interview Questions And Answers Python package Fuzzy project Gender Prediction us 15 days of Power BI Complete Microsoft Power BI Learn SQL LIKE Pattern Matching Tutorial 21 Essential Tools for Python Learn Power BI Calculate function Tutorial What is R? The Statistical Computing base for da How to Become a Data Scientist with No Experience ? SQL Joins Cheat Sheet Learn SQL Commands —25 Most Popular SQL Commands Creating Synthetic Data with Python Faker Tutorial How to Create and Sell Protable Online Courses: BLOG ARCHI VE

SELECTDISTINCT first_name FROMemployees

first_name

'___'

4.Useboth ‘%’ and ‘_’ tomatchanypattern

Code

SELECTDISTINCT first_name FROMemployees WHEREfirst_nameLIKE'%ann_'

Thepattern ‘%ann_’

5.Use NOT tofindstringsthatdonotmatchapattern

C Sharp

& Swift

Introduction to Journalism and Reporting

Introduction to Databases and SQL

How to Program in C++

Server 2008 Complete Video Training

Corel Presentations

Application Training

Cisco CCNP Implementing Cisco

Switched

August (72)

July (6)

June (1)

May (3)

April (11)

March (2)

February (6)

January (4)

2021 (31)

(6)

(19)

(54)

/1 /2 , :5://a .b .c /2 /0 9/l -s -l -p -m -t .h / Howmanywaysaretheretospell Le_n ?Thepatternwouldmatchanything from ‘Lexn’ , ‘LeAn’ , Le3n’ ,or ‘Le-n’ Whatarethedifferentnameswithonlythreecharacters?Wecanfindoutusingthreeconsecutive underscores___asthepattern.  Ofcourse,youcanuseboth ‘%’ and ‘_’ tocreateinterestingpatterns.
matchesastringthatstartswithanynumberofcharactersandends with ‘ann’ andoneothercharacter Whatifyouwanttofindallrowsthatdonotmatchaspecificcriterion?Youcanusethe NOT LIKE operator.Forexample,tofindalltitlesexceptforStaff,wecanusethesyntax Code COPY CODE Skills you'll gain: Analysis, Apache, Apache Spark, Basic Descriptive Statisti 4.6 (14 1k reviews) Beginner Specialization 3 6 Months Learn SQL Basics for Data Science Code
WHERE
LIKE
POWERED BY DATACAMP WORKSPACE COPY CODE
POWERED BY DATACAMP WORKSPACE COPY CODE
Code `WHEREtitleNOTLIKE‘Staff’` COPY CODE The Top 8 Most Important Reasons To Offer Online C Learn PCB design Online from anywhere 1000
Dot NET (C# NET) Interview Questions iOS
Most Important Interview Questions and 1000 interview question answers for IoS, php, andr IT books
Windows
X3
IP
Networks ►
► 2020
► 2019
► 2018
CAT EGORI ES 7 Days Drink Less (1) 70 697 (1) Afliate Marketing (4) All Batteries Alive (1) All World Radio (1) Name Email * Message * Send CONTACT FORM

Thisisexactlyequivalenttothesyntax

WHEREtitle!=‘Staff’

SELECTDISTINCT title FROMtitles

titleNOTLIKE'Staff'

Ofcourse,youcanuse `NOT LIKE` withanyofthepatternswedescribed.

SELECTDISTINCT title FROMtitles

titleNOTLIKE'%engineer'

6.Use LOWER (or UPPER )with LIKE forcase-insensitive patternmatching Code

Ifyouneedtoperformpatternmatchingbutaren’tsureifthestringisstoredinlowercase, uppercase,ormixedcase,youcanusethefollowingsyntax.

`LOWER(column_name)LIKEpattern`

Thefunction LOWER() returnsallstringsinlowercase,regardlessofwhethertheyarestoredas upper-,lower-ormixedcase.

Whenusingthesyntax,makesureyouspellthepatterninalllowercase!Else,youmightnotget anymatches.

/1 /2 , :5://a .b .c /2 /0 9/l -s -l -p -m -t .h /
 POWERED BY DATACAMP WORKSPACE COPY CODE Code
POWERED BY DATACAMP WORKSPACE COPY CODE Code
WHERE
POWERED BY DATACAMP WORKSPACE COPY CODE Code
WHERE
POWERED BY DATACAMP WORKSPACE COPY CODE
POWERED BY DATACAMP WORKSPACE COPY CODE

Data Science Fundamentals

Python and SQL

Youcouldreplace LOWER with UPPER inthesyntaxabovetoo.Besuretospelloutthepatternin CAPITALLETTERS.

Code

UPPER(column_name)LIKEPATTERN

POWERED BY DATACAMP WORKSPACE

Forexample,tofindoutifanemployee’snameisJoanne,JoAnne,Joanna,orJoAnna,tryeither ofthefollowing.

Code

SELECTDISTINCT first_name FROMemployees

WHERElower(first_name)LIKE'joann_'

POWERED BY DATACAMP WORKSPACE

Code

SELECTDISTINCT first_name FROMemployees

WHEREUPPER(first_name)LIKE'JOANN_'

POWERED BY DATACAMP WORKSPACE

7.SQL LIKE withMultipleValuesUsing OR/AND

Youcancombinemultipleconditionsusingthe LIKE syntaxtoo.

Forexample,usethe OR conditiontofindresultsthatsatisfyatleastoneoutof multiple LIKE patterns.

Code

SELECTDISTINCT first_name FROMemployees WHERE first_nameLIKE'Ad_l'OR first_nameLIKE'Ad_m'

CODE

CODE

/1 /2 , :5://a .b .c /2 /0 9/l -s -l -p -m -t .h /
with
COPY CODE
COPY
COPY

Ontheotherhand,tofindastringthatmatchesmultiple LIKE conditions,usethe AND keyword.

SELECTDISTINCT first_name FROMemployees WHERE first_nameLIKE'%am%'AND first_nameLIKE'%me%'

The LIKE syntaxcanbeappliedtomultiplecolumns,aslongastheirvariabletypeisavariablelengthcharacter( varchar ).Knowingthatwecanfindoutthenamesofemployeeswhoseinitials are ‘Z. Z.’

SELECTDISTINCT first_name,last_name FROMemployees WHERE first_nameLIKE'Z%'AND last_nameLIKE'Z%'

8.Use LIKE inthe SELECT CASE WHEN clause

Thusfar,wehavefocusedonusing LIKE asaconditionforselectingrecordsin the WHERE clause.Wealsouse LIKE inthe SELECT clausetoo.Forexample,canwefindout howmanyemployeeswiththename ‘Adam’ areinourdatabase?

/1 /2 , :5://a .b .c /2 /0 9/l -s -l -p -m -t .h /
  POWERED BY DATACAMP WORKSPACE COPY CODE Code
POWERED BY DATACAMP WORKSPACE COPY CODE Code
POWERED BY DATACAMP WORKSPACE COPY CODE
Skills you'll gain: Analysis, Analytics, Apache, Big Data, Cloud Computing, 4 8 (1 3k reviews) Beginner Specialization 3 6 Months Modern Big Data Analysis with SQL Skills you'll gain: Data Management, Databases, Statistical Programming, SQL 4 4 (11 reviews) Beginner Guided Project Less Than 2 Hours Understanding Basic SQL Syntax

SELECT

COUNT(CASEWHENfirst_nameLIKE'Adam'THEN1END)num_employees_adam FROMemployees

Ontheotherhand,howmanyemployeeshavetheinitials ‘A.Z.’ ?

SELECT

COUNT(CASEWHENfirst_nameLIKE'A%'ANDlast_nameLIKE'Z%'THEN1END)num_employees FROMemployees

IntermediateExamplesofSQLLIKE

The LIKE functionislargelysimilaracrossdifferentflavorsofSQL(e.g.PostgreSQL,MySQL, Redshift,etc.).Somehaveadditionalvariationsofthe LIKE functionthatareworthmentioning.

1.The ILIKE operator

AvailableinRedshiftandPostgreSQL, ILIKE isthecase-insensitiveversionof LIKE .Assuch, allofthefollowingareequivalent.

Code

SELECT

datacampILIKE‘datacamp’,--returnsTRUE DATACAMPILIKE‘datacamp’,--returnsTRUE DatacampILIKE‘datacamp’,--returnsTRUE datacampILIKE‘DataCamp’,--returnsTRUE

2.Usingsquarebrackets [] and [^] aswildcardcharacters

UsersofT-SQLorSQLServerhaveadditionalwildcardcharactersformorecomplexpattern matching.

Thesquarebracketsyntax [] matchesanysinglecharacterspecificwithintherangeorset.For example,thefollowingwillallreturnTRUE.

Code

SELECT

‘Carson’LIKE‘[CK]arson’,--returnsTRUEbecauseCisintherangeC-K ‘Karson’LIKE‘[CK]arson’,--returnsTRUEbecauseKisinrange ‘Larson’LIKE‘[CKL]arson’,--returnsTRUEbecauseLisintheset[CKL] ‘Parson’LIKE‘[CK]arson’--returnsFALSEbecausePisoutofrange

/1 /2 , :5://a .b .c /2 /0 9/l -s -l -p -m -t .h /
Code
POWERED BY DATACAMP WORKSPACE COPY CODE Code
POWERED BY DATACAMP WORKSPACE COPY CODE
POWERED BY DATACAMP WORKSPACE COPY CODE
POWERED BY DATACAMP WORKSPACE COPY CODE

3.The RLIKE operator

/1 /2 , :5://a .b .c /2 /0 9/l -s -l -p -m -t .h 9/ Thecaret-in-square-bracket [^] wildcardmatchesanysinglecharacterthatisnotwithinthe specifiedrangeorset.Canyouseewhythefollowingresultsaresuch? Here,since C iswithintherangeof [C-K] ,thepattern ‘C’ willnotmatch [^C-K] . Thus, ‘Carson’ willnotmatch ‘[^C-K]arson AvailableinMySQL,the RLIKE operatorrecognizesregularexpressions(RegEx)inthepattern. RegExisapowerfulandversatiletoolforadvancedpatternmatching. ItdoesnothurttohaveabasicunderstandingofRegEx,especiallyifyourflavorofSQLsupports RLIKE.YoucanlearnmoreaboutRegExwithourRegularExpressionsinPythoncourse.   Code SELECT ‘Carson’LIKE‘[^CK]arson’--returnsFALSE ‘Parson’LIKE‘[^CK]arson’--returnsTRUE POWERED BY DATACAMP WORKSPACE COPY CODE
Skills you'll gain: Computer Programming, Data Analysis, Data 4.4 (160 reviews) Beginner Specialization 3 6 Months Fundamentos de Ciencia de Datos con Python y SQL Skills you'll gain: Databases, Data Management, Statistical Programming, 4.4 (458 reviews) Intermediate Guided Project Less Than 2 Hours Intermediate Relational Database and SQL Code SELECTDISTINCT first_name FROMemployees WHEREfirst_nameRLIKE'Susann[a-e]' POWERED BY DATACAMP WORKSPACE COPY CODE 4.The ‘~~’ operator

UseSQLLIKEConfidently

LearnmoreaboutSQL

/1 /2 , :5://a .c /2 /0 9/l -s -l -p -m .h / InPostgreSQL, ‘~~’ iscompletelysynonymouswith LIKE .Therearealsoequivalents of ILIKE , NOT LIKE ,and NOT ILIKE Operator Equivalent ~~ LIKE ~~* ILIKE !~~ NOT LIKE !~~* NOT ILIKE MasteringSQLfunctionsiskeytosucceedingindatascience,andSQL’sLIKEcommandisno exception.GoodcommandoverSQLwillsuperchargeyouranalyticsprogress,sobesuretolearn itwell! FormoreresourcesonSQL,besuretocheckoutthefollowing:  IntroductiontoSQLCourse  SQLTutorialforBeginners  SQLBasicsCheatSheet
Masterthebasicsofquerying tablesinrelationaldatabases suchasMySQL,SQLServer, andPostgreSQL. IntermediateSQLQueries 4Hours 
Instructor Jointwoorthreetablestogether intoone,combinetablesusing settheory,andworkwith subqueriesinPostgreSQL. SQLforJoiningData 5Hours
/1 /2 ,://a .b .c /2 /0 9/l -s -l -p -m -t .h / Created By SoraTemplates | Distributed By Free Blogger Templates  PREVIOUS 21 Essential Tools for Python NEXT  15 days of Power BI Complete Microsoft Power BI Bootcamp  Facebook  Twitter  Google+  Pinterest  LinkedinSHARE THIS:     

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.
Learn SQL LIKE Pattern Matching Tutorial by ITExamtools - Issuu