- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to extract the area codes from a phone number with MySQL?
Let’s say we have a list of phone numbers and from that we want to get the area codes. These area codes are for example, the first 3 digits of the phone number. Use LEFT() function from MySQL for this.
Let us first create a table −
mysql> create table DemoTable -> ( -> AreaCodes varchar(100) -> ); Query OK, 0 rows affected (0.62 sec)
Insert some records in the table using insert command. Here, let’s say we have included the phone numbers −
mysql> insert into DemoTable values('90387568976') ; Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values('90389097878' ; Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values('56789008799'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values('45679008571'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values('45679008536); Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------------+ | AreaCodes | +------------+ | 90387568976| | 90389097878| | 56789008799| | 45679008571| | 45679008536| +------------+ 5 rows in set (0.00 sec)
Following is the query to get the available area codes −
mysql> select distinct LEFT(AreaCodes,4) from DemoTable
This will produce the following output −
+-------------------+ | left(AreaCodes,4) | +-------------------+ | 9038 | | 5678 | | 4567 | +-------------------+ 3 rows in set (0.13 sec)
Advertisements