✅ SQL String Functions

 

✅ SQL String Functions

  

🧠 1. What are String Functions?  

String functions are used to  

  • 👉 manipulate text data  
  • 👉 clean messy data  
  • 👉 format outputs  


Used heavily in:  

✔️ Data Analytics  

✔️ Reporting  

✔️ ETL processes  


⚡ 2. Common String Functions  

Function  : Purpose  

UPPER() : Convert to uppercase  

LOWER() : Convert to lowercase  

LENGTH() : Count characters  

CONCAT() : Join strings  

SUBSTRING() : Extract part of string  

TRIM() : Remove spaces  

REPLACE() : Replace text  


🔥 3. UPPER() & LOWER()

SELECT UPPER(name) AS upper_name FROM employees;

SELECT LOWER(name) AS lower_name FROM employees;


🔥 4. LENGTH()  

👉 Count number of characters

SELECT name, LENGTH(name) AS total_chars FROM employees;


🔥 5. CONCAT()  

👉 Combine strings

SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees;


🔥 6. SUBSTRING()  

👉 Extract part of string

SELECT SUBSTRING(name, 1, 3) FROM employees;

✔️ Extracts first 3 characters


🔥 7. TRIM()  

👉 Remove extra spaces

SELECT TRIM('   SQL   ');

✔️ Result → SQL


🔥 8. REPLACE()  

👉 Replace text inside string

SELECT REPLACE('I love Java', 'Java', 'SQL');


✔️ Result → I love SQL


🎯 9. Practice Tasks  

1. Convert names to uppercase  

2. Convert emails to lowercase  

3. Combine first & last names  

4. Extract first 4 letters of names  

5. Remove extra spaces from city names  


⚡ Mini Challenge 🔥  

👉 Create employee usernames using:  

first 3 letters of name + employee ID  


Example:  

Amit + 101 → Ami101  


🔥 Mini Challenge Solution 💯


👉 Requirement:  

Create username using:  

- First 3 letters of name  

- Employee ID  


Example:  

Amit + 101 → Ami101  


✅ SQL Solution

SELECT name,

       emp_id,

       CONCAT(SUBSTRING(name, 1, 3), emp_id) AS username

FROM employees;


✅ Example Output  

name : emp_id : username  

Amit : 101 : Ami101  

Neha : 102 : Neh102  

Ravi : 103 : Rav103  


🧠 How It Works  

👉 SUBSTRING(name, 1, 3)  

Extracts first 3 letters  


👉 CONCAT()  

Combines extracted text with employee ID  


🔥 Real-World Usage:  

String functions are commonly used for:  

👉 Username generation  

👉 Email formatting  

👉 Data cleaning  

👉 Customer IDs 💯

No comments:

Post a Comment

Infolinks In Text Ads