SQL String Functions π€ΒΆ
Prerequisites: SELECT Statement
Mentor's Note: Data in the real world is messy. People type their names in lowercase, add extra spaces, or provide long codes where you only need the first 3 letters. String functions are your "Formatting Tools" to clean this up. π‘
π The Scenario: The Name Badge Maker πΒΆ
Imagine you are printing name badges for a conference. - The Problem: A user typed their name as " vISHNU damwala ". - The Action: 1. TRIM: Remove the extra spaces. βοΈ 2. UPPER: Make it all capitals for visibility. β¬οΈ - The Result: "VISHNU DAMWALA" β
π» 1. Case Conversion (UPPER & LOWER)ΒΆ
Used to standardize text casing.
-- Scenario: Find a user regardless of how they typed their name
SELECT * FROM users
WHERE UPPER(name) = 'VISHNU';
-- Output: 'vishnu', 'Vishnu', and 'VISHNU' will all match!
π» 2. Cleanup (TRIM, LTRIM, RTRIM) βοΈΒΆ
Removes leading and trailing spaces.
-- Scenario: Clean up messy data imports
SELECT TRIM(' Hello ') AS "Clean" FROM dual;
-- Result: 'Hello'
π» 3. Extraction (SUBSTR / SUBSTRING) π°ΒΆ
Used to "slice" a piece of text.
π» 4. Length & Search (LENGTH & INSTR) πΒΆ
- LENGTH: Counts characters.
- INSTR: Finds the position of a character.
-- Scenario: Find the position of the '@' in an email
SELECT INSTR('[email protected]', '@') FROM dual;
-- Result: 7