Skip to content
Advertisement

SQL: Add some validation steps for phone number

I have a fairly simple bit of SQL code that’s truncating three fields into one called “phone_number”:

Select pp.country_code_number||pp.area_code||pp.phone_number AS phone_number

What I’d like to do is:

  1. Remove any non numeric values in the data (some values have “07111-245 123” for example which I’d like to convert to “07111245123”

  2. If country code = “44” then only return the pp.phone_number AS phone_number ELSE return “+” and pp.country_code_number||pp.area_code||pp.phone_number AS phone_number

Advertisement

Answer

Introduction

Considering I didn’t know the database, I implemented this in Oracle, PostgresSql and also MySQL. These are the 3 databases that (in my experience) most commonly use || for concatenation (see: https://www.databasestar.com/sql-concatenate/ ).

What you need are two things:

  • A string manipulation function to remove all non-numeric characters. In my example I used a stored procedure. Maybe a replace like Forpas example is good too (depending on your requirements ). In oracle you can also use REGEXP_REPLACE, see Oracle: Replacing non-numeric chars in a string .
  • A Case expression or (decode in oracle also works) .

Example (Oracle SQL)

Example (Postgres)

Link: https://www.db-fiddle.com/f/p6ziyWyWCGXTCiyiYSSyS8/2

Example (MySQL)

DDL

Link: https://www.db-fiddle.com/f/p6ziyWyWCGXTCiyiYSSyS8/1

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement