- 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 select all distinct filename extensions from a table of filenames in MySQL?
You can use DISTINCT along with SUBSTRING_INDEX() to extract the filename extensions. Let us first create a table−
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FileName text ); Query OK, 0 rows affected (0.75 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable(FileName) values('AddTwoValue.java'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(FileName) values('Image1.png'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(FileName) values('MultiplicationOfTwoNumbers.java'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(FileName) values('Palindrome.c'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(FileName) values('FoodCart.png'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable(FileName) values('Permutation.py'); Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output−
+----+---------------------------------+ | Id | FileName | +----+---------------------------------+ | 1 | AddTwoValue.java | | 2 | Image1.png | | 3 | MultiplicationOfTwoNumbers.java | | 4 | Palindrome.c | | 5 | FoodCart.png | | 6 | Permutation.py | +----+---------------------------------+ 6 rows in set (0.00 sec)
Following is the query to select all distinct filename extensions from a table of filenames−
mysql> SELECT DISTINCT SUBSTRING_INDEX(FileName,'.',-1) FROM DemoTable;
This will produce the following output−
+----------------------------------+ | SUBSTRING_INDEX(FileName,'.',-1) | +----------------------------------+ | java | | png | | c | | py | +----------------------------------+ 4 rows in set (0.03 sec)
Advertisements