Fix the Capitalisation of Registered Names — SQL Easy Problem
Students typed their names into the tech-fest registration form in whatever case they liked — aRJUN, PRIYA, kavya.
- Difficulty: Easy
- Topics: Strings
- Dialect: MySQL
- Problem: #40
Problem statement
Students typed their names into the tech-fest registration form in whatever case they liked — aRJUN, PRIYA, kavya.
Return reg_id and student_name, with each name fixed so that only the first letter is a capital and every other letter is small, ordered by reg_id ascending. Every name is a single word made only of English letters.
Tables
Table: Registration
| Column | Type |
|---|---|
| reg_id | int |
| student_name | varchar |
Primary key: reg_id.
One row per registration; student_name is exactly what the student typed, never NULL or empty.
Examples
Example 1
Registration
| reg_id | student_name |
|---|---|
| 3 | aRJUN |
| 1 | priya |
| 2 | KAVYA |
| 5 | Ira |
| 4 | nIKHIL |
| 6 | om |
Output
| reg_id | student_name |
|---|---|
| 1 | Priya |
| 2 | Kavya |
| 3 | Arjun |
| 4 | Nikhil |
| 5 | Ira |
| 6 | Om |
How to solve Fix the Capitalisation of Registered Names
Split each name into its first character and the rest, fix the case of each part, and join them back:
LEFT(student_name, 1)(orSUBSTRING(student_name, 1, 1)) is the first letter, andUPPERmakes it a capital;SUBSTRING(student_name, 2)is everything from the second character on, andLOWERmakes it small letters — for a two-letter name likeomit is a single letter, and the method needs no special case;CONCATjoins the two parts.
Alias the result AS student_name, or the column is named after the whole expression. The comparison of your output with the expected one is case-sensitive, which is the point of the exercise: aRJUN must become exactly Arjun.
Another way to take the rest of the name is RIGHT(student_name, CHAR_LENGTH(student_name) - 1) — the last length − 1 characters. CHAR_LENGTH counts characters while MySQL's LENGTH counts bytes; for plain English letters they agree, but CHAR_LENGTH is the right habit for text, since a name with an accented or Devanagari letter takes more than one byte per character.
Finally ORDER BY reg_id gives the order the statement asks for. The work per row is constant, so the query is linear plus the sort.
Reference solution (MySQL)
SELECT reg_id,
CONCAT(UPPER(LEFT(student_name, 1)), LOWER(SUBSTRING(student_name, 2))) AS student_name
FROM Registration
ORDER BY reg_idAnother way
SELECT reg_id, CONCAT(UCASE(SUBSTR(student_name, 1, 1)), LCASE(SUBSTR(student_name, 2))) AS student_name FROM Registration ORDER BY reg_idAnother way
SELECT reg_id, CONCAT(UPPER(LEFT(student_name, 1)), LOWER(RIGHT(student_name, CHAR_LENGTH(student_name) - 1))) AS student_name FROM Registration ORDER BY reg_id ASC← Busy Streaks at the Book Fair · Students Registered for a Machine Learning Elective →