Using the function INSERT
To add characters to a result, you can use the function INSERT
. Not to be confused with the syntax INSERT INTO
, we are talking about the function of string.
SELECT INSERT( INSERT( INSERT( cpf, 10, 0, '-' ), 7, 0, '.' ), 4, 0, '.' )
Explaining:
the INSERT
more internal adds the -
at the tenth position, and removes 0 characters (the second numeric parameter serves for substitution instead of insertion only)
the following two add the points in the correct places.
Syntax:
INSERT(str,pos,len,newstr)
│ │ │ └───── string a ser inserida
│ │ └────────── quantos caracteres serão deletados na posição
│ └────────────── posição onde a string será inserida
└────────────────── campo desejado ou string original
Equivalent in PHP:
substr_replace(substr_replace(substr_replace( $cpf, '-', 9, 0 ), '.', 6, 0 ), '.', 3, 0 );
An alternative would be to use SUBSTR
to take each "piece" of the CPF, and paste the pieces and dividers using CONCAT
:
SELECT CONCAT(SUBSTR(cpf,1,3),'.',SUBSTR(cpf,4,3),'.',SUBSTR(cpf,7,3),'-',SUBSTR(cpf,10,2))
I think the INSERT
is nicer in this case (at least much shorter to write, besides referencing the field in one place).
In any case, the second example may be useful for other uses. It is not as noble as a kintsugi, but the CONCAT
has its moments of glory.
Equivalent in PHP:
substr($cpf,0,3).'.'.substr($cpf,3,3).'.'.substr($cpf,6,3).'-'.substr($cpf,9,2);
Because I’m building a Webservice that returns a JSON with the client list. then wanted to avoid having to make another loop in PHP, because of performance.
– GilCarvalhoDev
Anyway to do in Mysql (in Query) would pass the PHP process to Mysql. So somehow someone would make the service format the CPF.
– Inkeliz
If the usage is purely visual, you can do this in javascript as it would save unnecessary executions on the server, even if they are small, imperceptible executions.. You wouldn’t need to "go through the data again" in case you format in js.
– Daniel Omine