create table phone_log(phone_number CHAR(20) NOT NULL,
area_code CHAR(10));
INSERT INTO phone_log(phone_number)
VALUES ('310-430-9201');
INSERT INTO phone_log(phone_number)
VALUES ('917-829-2876');
INSERT INTO phone_log(phone_number)
VALUES ('424-917-1055')
How do I insert the area code of each phone number using the SUBSTRING FUNCTION for each row?
I want the result to be like below:
2
Answers
Using the substring function update in existing row is done. try the below query: –
If the
area_code
can vary in length (which is usually the case), I suggestsplit_part()
:See:
If you must store the functionally dependent value for
area_code
redundantly (which I would try to avoid), consider a generated column:Then your original simple
INSERT
commands just work.See:
Either way, you do not want to use
char(n)
, which is short forcharacter(n)
. Usetext
orvarchar(n)
instead. See:fiddle