10. Text Functions Analysts Use Daily
10.4 How to Cut Text with substr()
Why. Codes often carry meaning in fixed places. The first three letters of a tracking code can tell you the city, and the end can be a serial number.
What. substr(text, start, length) returns a piece of the text. The first character is position 1, not 0. If you leave out the length, you get everything to the end. In SQLite a negative start counts from the right, so substr(code, -5) gives the last five characters. Other databases treat a negative start differently, so check before you move the query.
How. Cut each tracking code into a city code, a hub code part and a serial number.
Steps
- Run the example for shipments 1001 and 1006.
- Read city_code: positions 1 to 3.
- Read hub_part: positions 1 to 6, which should match hubs.hub_code.
- Read serial: the last five characters, taken with a negative start.
Examples
Example 1 · dataset: swiftship_logistics
SELECT tracking_code,
substr(tracking_code, 1, 3) AS city_code,
substr(tracking_code, 1, 6) AS hub_part,
substr(tracking_code, -5) AS serial
FROM shipments
WHERE shipment_id IN (1001, 1006);Output
| tracking_code | city_code | hub_part | serial |
|---|---|---|---|
| PNQ-01-00017 | PNQ | PNQ-01 | 00017 |
| LHR-03-00221 | LHR | LHR-03 | 00221 |
Meaning. PNQ-01-00017 splits into PNQ, PNQ-01 and 00017. LHR-03-00221 splits into LHR, LHR-03 and 00221. This works because every code here has the same fixed layout.
Ravindra Bagale's Tip
Fixed positions work only when every value has the same layout. If the lengths vary, find the separator with instr() first and cut from there.
Ravindra Bagale's Tip – मराठी
ठराविक जागा तेव्हाच चालतात जेव्हा प्रत्येक value ची रचना सारखी असते. Lengths बदलत असतील तर आधी instr() ने separator शोधा आणि तिथून तुकडा काढा.
Ravindra Bagale's Tip – हिंदी
तय जगहें तभी काम करती हैं जब हर value की बनावट एक जैसी हो। लंबाई बदलती हो तो पहले instr() से separator ढूँढिए और वहाँ से काटिए।