Lessons › SQL › Chapter 8: Text, dates and safe maths
SQL lesson
Part of a text: LEFT, RIGHT and SUBSTRING
Codes often hide useful parts. In LAG-2026-0001 the first 3 letters are the store, the middle is the year, and the end is the order number. LEFT takes characters from the start, RIGHT from the end, and SUBSTRING from the middle. Positions start at 1.
Try this lesson free →Example
Take just the bit you need
SELECT order_code, LEFT(order_code, 3) AS store_code
FROM orders| order_code | store_code |
|---|---|
| LAG-2026-0001 | LAG |
| ABJ-2026-0002 | ABJ |
| ACC-2025-0003 | ACC |
| LAG-2026-0004 | LAG |
| ABJ-2025-0005 | ABJ |
| ACC-2026-0006 | ACC |
Step by step
- The first 3 characters: LAG.
SELECT order_code, LEFT(order_code, 3) AS store_code FROM orders - The last 4 characters: 0001.
SELECT order_code, LEFT(order_code, 3) AS store_code FROM orders - 4 characters starting at the 5th. L-A-G-dash are positions 1 to 4, so the year starts at 5: 2026.
SELECT order_code, LEFT(order_code, 3) AS store_code FROM orders
Practice
1. Using orders, show order_code and the store code, the first 3 characters of order_code. Name it store_code.
SELECT order_code, LEFT(order_code, 3) AS store_code FROM orders2. Using products, show product_id and the department code, the first 2 characters of sku. Name it dept.
SELECT product_id, LEFT(sku, 2) AS dept FROM productsLearn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →