BBampaa

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 →
About 5–10 minutes · no sign-up needed

Example

Take just the bit you need

SELECT order_code, LEFT(order_code, 3) AS store_code
FROM orders

Result:

order_codestore_code
LAG-2026-0001LAG
ABJ-2026-0002ABJ
ACC-2025-0003ACC
LAG-2026-0004LAG
ABJ-2025-0005ABJ
ACC-2026-0006ACC

Step by step

  1. The first 3 characters: LAG.
    SELECT order_code, LEFT(order_code, 3) AS store_code FROM orders
  2. The last 4 characters: 0001.
    SELECT order_code, LEFT(order_code, 3) AS store_code FROM orders
  3. 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

Try each one in your head first, then open the answer.

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 orders
2. 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 products

Learn 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 →
About 5–10 minutes · no sign-up needed