Ravindra BagaleCourses & study guides Track your progress

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

  1. Run the example for shipments 1001 and 1006.
  2. Read city_code: positions 1 to 3.
  3. Read hub_part: positions 1 to 6, which should match hubs.hub_code.
  4. 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_codecity_codehub_partserial
PNQ-01-00017PNQPNQ-0100017
LHR-03-00221LHRLHR-0300221

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.