How to get file extension of file as a result of MySQL query?


In order to get file extension of file as a result of SQL query, you can use SUBSTRING_INDEX().

The syntax is as follows

select substring_index(yourColumnName,'.',-1) as anyAliasName from yourTableName;

To understand the above syntax, let us create a table. The query to create a table is as follows

mysql> create table getFileExtensionDemo
   -> (
   -> File_Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> File_Name text
   -> );
Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert command.

The query is as follows

mysql> insert into getFileExtensionDemo(File_Name) values('John.AllMySQLConcept.doc');
Query OK, 1 row affected (0.17 sec)
mysql> insert into getFileExtensionDemo(File_Name) values('Introductiontojava.txt');
Query OK, 1 row affected (0.17 sec)
mysql> insert into getFileExtensionDemo(File_Name) values('C and C++.AllDataStructureandAlgorithm.pdf');
Query OK, 1 row affected (0.14 sec)
mysql> insert into getFileExtensionDemo(File_Name) values('C.Users.Desktop.AllMySQLScript.sql');
Query OK, 1 row affected (0.39 sec)

Display all records from the table using select statement.

The query is as follows

mysql> select *from getFileExtensionDemo;

The following is the output

+---------+--------------------------------------------+
| File_Id | File_Name                                  |
+---------+--------------------------------------------+
| 1       | John.AllMySQLConcept.doc                   |
| 2       | Introductiontojava.txt                     |
| 3       | C and C++.AllDataStructureandAlgorithm.pdf |
| 4       | C.Users.Desktop.AllMySQLScript.sql         |
+---------+--------------------------------------------+
4 rows in set (0.00 sec)

Here is the query to get the extension of file as a result of query

mysql> select substring_index(File_Name,'.',-1) as AllFileExtension from getFileExtensionDemo;

The following is the output with only the file extensions

+------------------+
| AllFileExtension |
+------------------+
| doc              |
| txt              |
| pdf              |
| sql              |
+------------------+
4 rows in set (0.20 sec)

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements