Parsing and Formatting Strings
SUBSTRING, position, splitting, and case conversion across dialects.
Why String Functions Get Asked
Real data is messy: full names that need splitting, email domains to extract, codes embedded in IDs, inconsistent casing. Interviewers use string manipulation to see if you can clean and reshape text without exporting to a script.
As with dates, the functions are only loosely standardized, so the goal is to know the concept and the common variants.
- Substring extraction and position
- Concatenation
- Splitting and replacing
- Case conversion and trimming
SUBSTRING and Position
SUBSTRING(s FROM start FOR length) is the SQL-standard form; most engines also accept SUBSTRING(s, start, length). String positions are 1-based, a classic off-by-one trap for programmers used to 0-based languages.
POSITION(sub IN s) (or STRPOS/CHARINDEX) finds where a substring begins, returning 0 when not found.
SELECT
SUBSTRING('INV-2024-042' FROM 5 FOR 4) AS year, -- '2024'
POSITION('-' IN 'INV-2024-042') AS first_dash; -- 4All lessons in this course
- Date Arithmetic and Intervals
- Truncating and Bucketing Dates
- Parsing and Formatting Strings
- Time Zones and Timestamps