Leetcode SQL 50 -- 1667. Fix Names in a Table

  1. Question
    1. Table name: Users
  2. Explaination
    1. SQL SUBSTRING() Function
    2. SQL UPPER(), LOWER(), and CONCAT()
  3. Solution

Question

Table name: Users

Column Name Type
user_id int
name varchar

This table contains the user_id and the name of the user. The name consists of only lowercase and uppercase characters.

Write a solution to fix the names so that only the first character is uppercase and the rest are lowercase.
Return the result table ordered by user_id.
The result format is in the following example.

Explaination

We can split the tasks into three part.

  1. Split the name into first character and the remaining charactersSUBSTRING()
  2. Modify them into upper case and lower case respectively → UPPER() and LOWER()
  3. Order the result by user_idORDER BY

SQL SUBSTRING() Function

For extracting characters from a string, we can use the function SUBSTRING(<string>, start, end).
For example,

SUBSTRING(name, 1, 1)

returns the first character from string name,
and name without the first letter.

SUBSTRING(name, 2, LENGTH(name))

SQL UPPER(), LOWER(), and CONCAT()

For text converting, we can simply use UPPER(<text>) and LOWER(<text>).
Then we can combine two substring together by using

CONCAT(<string1>, <string2>, ... , <string_n>)

and finally, use ORDER BY user_id.

Solution

SELECT user_id, 
  CONCAT(
    UPPER(SUBSTRING(name, 1, 1)), 
    LOWER(SUBSTRING(name, 2, LENGTH(name)))
  ) AS name
FROM Users
ORDER BY user_id

More SQL 50 questions: here


Please cite the source for reprints, feel free to verify the sources cited in the article, and point out any errors or lack of clarity of expression. You can comment in the comments section below or email to GreenMeeple@yahoo.com
This Repo