Use the text functions SUBSTR()/MID(), LEFT(), RIGHT() and INSTR()
Expt. No.32
Page No.64
SUBSTR, LEFT, RIGHT, INSTR
Aim
To extract parts of teacher names with SUBSTR()/MID(), LEFT() and RIGHT(), and find the position of a character with INSTR().
Concepts used
Queries
USE school;SELECT tname, LEFT(tname, 3), RIGHT(tname, 3), SUBSTR(tname, 2, 4) FROM teacher;SELECT tname, MID(tname, 1, INSTR(tname, ' ') - 1), INSTR(tname, 'a') FROM teacher;
A marked line continues the line above it. In your file, write it on the same line.
Table used
Table: teacher
+-----+------------+---------+--------+------------+ | tid | tname | subject | salary | doj | +-----+------------+---------+--------+------------+ | 1 | Meena Rao | Maths | 72000 | 2012-07-16 | | 2 | Arun Kumar | Physics | 68000 | 2015-04-01 | | 3 | Sana Khan | IP | 75000 | 2010-11-23 | | 4 | Vikas Jain | English | 61000 | 2019-06-10 | +-----+------------+---------+--------+------------+
Output
mysql> USE school;
Database changed
mysql> SELECT tname, LEFT(tname, 3), RIGHT(tname, 3), SUBSTR(tname, 2, 4) FROM teacher;
+------------+----------------+-----------------+---------------------+
| tname | LEFT(tname, 3) | RIGHT(tname, 3) | SUBSTR(tname, 2, 4) |
+------------+----------------+-----------------+---------------------+
| Meena Rao | Mee | Rao | eena |
| Arun Kumar | Aru | mar | run |
| Sana Khan | San | han | ana |
| Vikas Jain | Vik | ain | ikas |
+------------+----------------+-----------------+---------------------+
4 rows in set
mysql> SELECT tname, MID(tname, 1, INSTR(tname, ' ') - 1), INSTR(tname, 'a') FROM teacher;
+------------+--------------------------------------+-------------------+
| tname | MID(tname, 1, INSTR(tname, ' ') - 1) | INSTR(tname, 'a') |
+------------+--------------------------------------+-------------------+
| Meena Rao | Meena | 5 |
| Arun Kumar | Arun | 1 |
| Sana Khan | Sana | 2 |
| Vikas Jain | Vikas | 4 |
+------------+--------------------------------------+-------------------+
4 rows in set
✓ Printed by running this query set, not typed by hand.
Result
LEFT and RIGHT took the first and last 3 characters, and SUBSTR(tname, 2, 4) took 4 characters starting from the second. INSTR found the position of the space, so MID could cut out each first name ("Meena", "Arun", …). INSTR(tname, 'a') gave the first position of "a" or "A", since MySQL ignores case here.
Viva voce: what the examiner may ask
01From which position does SUBSTR start counting?
1. The first character is at position 1, not 0.
02What does INSTR return if the substring is not found?
0.
03Are SUBSTR and MID the same?
Yes. MID is another name for SUBSTR.
Variations for the lab test
- Display the surname of each teacher using SUBSTR and INSTR.
- Display the first letter of each subject.
- Display the teachers whose name has "a" as the second letter using MID.
! Common mistake Writing
SUBSTR(tname, 0, 3) returns an empty string, because positions start at 1.