
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Minimum and Maximum Values from a Hyphen-Separated String in MySQL
Use MIN() function along with SUBSTRING() for minimum, whereas MAX() for maximum. Let us first create a table −
mysql> create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Value varchar(100) -> ); Query OK, 0 rows affected (0.76 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Value) values('10-20'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable(Value) values('200-100'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(Value) values('780-235'); Query OK, 1 row affected (0.29 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+---------+ | Id | Value | +----+---------+ | 1 | 10-20 | | 2 | 200-100 | | 3 | 780-235 | +----+---------+ 3 rows in set (0.00 sec)
Following is the query to find the MIN() and MAX() value from the number substrings separated from a string with hyphen −
mysql> select min(SUBSTRING_INDEX(Value, '-', 1)), -> max(SUBSTRING_INDEX(Value, '-', -1)) -> from DemoTable;
This will produce the following output −
+-------------------------------------+--------------------------------------+ | min(SUBSTRING_INDEX(Value, '-', 1)) | max(SUBSTRING_INDEX(Value, '-', -1)) | +-------------------------------------+--------------------------------------+ | 10 | 235 | +-------------------------------------+--------------------------------------+ 1 row in set (0.04 sec)
Advertisements