3

I have a table such as the below

    Name
    firstname lastname
    FirstName Lastname
    firstName Lastname
    FirstName lastname

I am trying to capitalize each letter of the firstname and lastname to be Firstname Lastname in all the 4 cases.

Any recommendations on the query without using the CAP_FIRST function? Can I use regex?

Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
Stackoverflow User
  • 161
  • 1
  • 4
  • 10
  • 1
    Why can't you use `CAP_FIRST`? – Schwern Mar 17 '16 at 22:18
  • Possible duplicate of [MySQL - Capitalize first letter of each word, in existing table](http://stackoverflow.com/questions/3278207/mysql-capitalize-first-letter-of-each-word-in-existing-table) – Schwern Mar 17 '16 at 22:18
  • 1
    From the examples you provided it looks like you're wanting to also convert all of the other letters to lowercase. This may not be ideal for `Firstname McLastname`, etc. – Don't Panic Mar 17 '16 at 22:29
  • Yes, You got it right...need to lowercase the rest of the alphabets – Stackoverflow User Mar 18 '16 at 00:36
  • As explained in [this answer](https://stackoverflow.com/a/67399882/4227328), you can create the function to do that. – Ali A. Jalil Jun 05 '21 at 11:10

2 Answers2

6

This is a query that works:

SELECT 
CONCAT(
    UPPER(SUBSTRING(Name,1,1)),
    LOWER(SUBSTRING(Name,2,Locate(' ', Name)-1)),
    UPPER(SUBSTRING(Name,Locate(' ', Name)+1,1)),
    LOWER(SUBSTRING(Name,Locate(' ', Name)+2)))
FROM NameTable;

This the result:

Name
Firstname Lastname
Firstname Lastname
Firstname Lastname
Firstname Lastname

To UPDATE column use,

UPDATE NameTable 
SET NameTable.Name = CONCAT(
    UPPER(SUBSTRING(Name,1,1)),
    LOWER(SUBSTRING(Name,2,Locate(' ', Name)-1)),
    UPPER(SUBSTRING(Name,Locate(' ', Name)+1,1)),
    LOWER(SUBSTRING(Name,Locate(' ', Name)+2)));

Regards

White Feather
  • 2,733
  • 1
  • 15
  • 21
0

This is a fix of White Feather answer,

The fix to avoid duplication of first character is to add IF condition in this part

UPPER(SUBSTRING(Name,1,1))

The original code is like this

SELECT 
CONCAT(
    UPPER(SUBSTRING(Name,1,1)),
    LOWER(SUBSTRING(Name,2,Locate(' ', Name)-1)),
    UPPER(SUBSTRING(Name,Locate(' ', Name)+1,1)),
    LOWER(SUBSTRING(Name,Locate(' ', Name)+2)))
FROM NameTable;

Then updated version will be like this

SELECT 
CONCAT(
    IF(INSTR(t1.firstname, ' ') > 0, UPPER(SUBSTRING(Name,1,1)),''),
    LOWER(SUBSTRING(Name,2,Locate(' ', Name)-1)),
    UPPER(SUBSTRING(Name,Locate(' ', Name)+1,1)),
    LOWER(SUBSTRING(Name,Locate(' ', Name)+2)))
FROM NameTable;

But this only supports two words, if you have three or more it cannot be capitalized.

bdalina
  • 503
  • 10
  • 16