🔥🔥 2 Solutions in MySQL | Beats 96.63%🔥🔥
💡 Solution 1: Using REGEX, SUBSTR(), LIKE & LOCATE() - Beats 96.63%💡 Intuition🔍 The task is to filter valid email addresses from a table. My initial thought was
# 💡 Solution 1: Using REGEX, SUBSTR(), LIKE & LOCATE() - Beats 96.63%

# 💡 Intuition

🔍 The task is to filter valid email addresses from a table. My initial thought was:

We’re looking for:

✅ A username (before @) with only letters, numbers, and _.

✅ A domain name (after @) containing only letters.

✅ A domain that ends with .com.

# 🧠 Approach
We break down the email into parts using LOCATE() and SUBSTR() functions and validate them using REGEXP:

 1. 🔗 **Structure Check**:
    email LIKE '%@%.com' ensures the format is close to something@domain.com.
 2. ✍️ **Username Validation**: SUBSTR(email, 1, LOCATE('@', email) - 1) 

 3. 🌐 **Domain Validation**: SUBSTR(email, LOCATE('@', email) + 1, LENGTH(email) - LOCATE('@', email) - 4)
 4. 🧹 **Sorting**: We use ORDER BY user_id for a clean and predictable result.

# 📊 Complexity
- ⏱ Time complexity: **O(n*m)**
Where n is the number of users and m is the average email length due to string manipulation and regex matching.

- 🧠 Space complexity: **O(n)**

# Code
```mysql []
SELECT 
    *
FROM users
WHERE email LIKE '%@%.com'
    AND SUBSTR(email, 1, LOCATE('@', email) - 1) REGEXP '^[a-zA-Z0-9_]+$'
    AND SUBSTR(email,
        LOCATE('@', email) + 1,
        LENGTH(email) - LOCATE('@', email) - 4) REGEXP '^[a-zA-Z]+$'
ORDER BY user_id;
```
# 💡 Solution 2: Using REGEX only - Beats 5.51%

# 💡 Intuition
🔍 The goal is to filter out emails that are valid based on a strict pattern:

✅ The local part (before @) contains only alphanumeric characters and underscores.

✅ The domain contains only alphabetic characters.

✅ The email ends with .com.

Using a single regular expression, we can match the entire structure of the email without breaking it down manually.

# 🧠 Approach
   ```
    1. Regex Match: The regex '^[a-zA-Z0-9_]+@[a-zA-Z]+.(com)$' does the following
    2. ^[a-zA-Z0-9_]+ → ensures the local part starts at the beginning and has only valid characters.
    3. @ → ensures presence of a single @.
    4. [a-zA-Z]+ → validates domain name (only letters).
    5. .(com)$ → ensures it ends with .com.
```


# 📊 Complexity
⏱ Time Complexity: **𝑂(𝑛*𝑚)**
Where n is the number of rows in the users table, and m is the length of the email string (due to regex evaluation).

🧠 Space Complexity: **O(n)** auxiliary memory in most engines

# Code
```mysql []
SELECT 
    *
FROM users
WHERE email REGEXP '^[a-zA-Z0-9_]+@[a-zA-Z]+.(com)$'
ORDER BY user_id;
```


['Database', 'MySQL']