Syntax error Getting the first part from the Postcode in MySQL

Getting the first part from the Postcode in MySQL



To get the first part, use SUBSTRING(). Let us first create a table −

mysql> create table DemoTable858(PostCode varchar(100));
Query OK, 0 rows affected (0.56 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable858 values('US90 456');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable858 values('UK1 EN789343');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable858 values('ENG78884 736454654');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable858;

This will produce the following output −

+--------------------+
| PostCode           |
+--------------------+
| US90 456           |
| UK1 EN789343       |
| ENG78884 736454654 |
+--------------------+
3 rows in set (0.00 sec)

Following is the query to get the first part from Postcode −

mysql> select substring(PostCode, 1, locate (' ', PostCode) - 1) AS GetFirstPart from DemoTable858;

This will produce the following output −

+--------------+
| GetFirstPart |
+--------------+
| US90         |
| UK1          |
| ENG78884     |
+--------------+
3 rows in set (0.00 sec)
Updated on: 2019-09-03T12:41:17+05:30

224 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements