Similar Problems

Similar Problems not available

Fix Names In A Table - Leetcode Solution

Companies:

LeetCode:  Fix Names In A Table Leetcode Solution

Difficulty: Easy

Topics: database  

Problem statement:

Given a table "students" with columns "id" and "name". Change the name of students whose name has a lowercase first letter to have an uppercase first letter. Return the entire table.

Example 1:

Input:

| id | name | |----|--------| | 1 | mary | | 2 | anna | | 3 | john |

Output:

| id | name | |----|--------| | 1 | Mary | | 2 | Anna | | 3 | John |

Solution:

One possible solution to this problem is to use the built-in function UPPER() in SQL to change the first letter of the name to uppercase. We can achieve this by using a conditional case statement in the SELECT clause to check whether the first letter of the name is lowercase or not, and apply UPPER() if it is lowercase.

The SQL query for this solution is as follows:

SELECT id, 
       CASE 
         WHEN LOWER(SUBSTR(name, 1, 1)) = SUBSTR(name, 1, 1) THEN UPPER(SUBSTR(name, 1, 1)) || SUBSTR(name, 2)
         ELSE name
       END AS name
FROM students;

In this query, we first select the id column as it is, then define a new column called name using the CASE statement. The CASE statement checks whether the first letter of the name is lowercase or not by using the LOWER() function to convert the first letter to lowercase and comparing it with the first letter directly. If they are equal, then the first letter is lowercase and we apply UPPER() to it using the concatenation operator || with the rest of the name. Otherwise, the name is already in uppercase, so we simply output it as is.

Finally, we select this new table with the updated names using the FROM clause and table name "students".

This solution should work for any number of rows in the "students" table and correctly update the names of those students whose name has a lowercase first letter.

Fix Names In A Table Solution Code

1