Brightlane's order reference system extracts the date portion from structured order codes. Each code follows the format 'ORD-YYYY-MM-DD'.
Write a query to return the 10-character segment starting at position 5 of the order code 'ORD-2024-03-15'.
Output:
- A single row with one column,
order_date, containing the extracted segment.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
SUBSTRING('ORD-2024-03-15', 5, 10) AS order_date The shape
SUBSTRING('ORD-2024-03-15', 5, 10) returns the ten characters starting at position 5 of the order code, which is exactly the YYYY-MM-DD date portion after the three-character ORD- prefix. SUBSTRING is 1-indexed, so position 5 is the first character after the prefix and its leading hyphen.
Clause by clause
SELECT SUBSTRING('ORD-2024-03-15', 5, 10) AS order_dateslices the literal and labels the resultorder_date. The three arguments are the source string, the start position, and the length: start at character5(the2in2024) and take ten characters from there, which lands on the closing5of'15'. The result is the literal substring'2024-03-15'.- There is no
FROMbecause the input is the literal itself.SUBSTRINGis a scalar function that operates on one string and returns one string.
Why this and not parsing the date directly
The output spec asks for the ten-character segment, not a typed date. SUBSTRING returns text, which is what the order-reference system reads. Wrapping the result in ::date or any other cast would change the column type and overshoot what the task is asking for. When the structure is a known fixed-width prefix followed by the value, position-based extraction is the cleanest tool.
The trap
SUBSTRING is 1-indexed, not 0-indexed. A reader coming from a language where the first character is at index 0 will write SUBSTRING('ORD-2024-03-15', 4, 10) and get '-2024-03-1' with a leading hyphen and a missing final 5. The fix is the indexing convention: position 1 is the first character, position 2 is the second, and position 5 is the first character past the four-character ORD- prefix. Counting from one is the rule for every SQL string-position function in PostgreSQL.
You practiced SUBSTRING(string, start, length) with 1-indexed positions — extract a fixed-width slice from a structured code.