Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create table like another table with additional columns in MYSQL

I have ‘Name, Age, Gender’ columns in a ‘test’ table.

I now, want to create another table ‘test1’ which will have these columns :
‘Name, Age, Gender, Occupation’.

How do I do it without creating and then altering? Is there any way to do it in a single line?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried adding one column, but I was able to add it at the start only, like:
CREATE TABLE test1 (Occupation VARCHAR(50)) LIKE test;

This would result in ‘Occupation, Name, Age, Gender’.

I tried CREATE TABLE test1 LIKE test (Occupation VARCHAR(50)) which gave me an error.

How to add columns at last while creation?

>Solution :

You may use CREATE TABLE AS ... with a select containing the new column:

CREATE TABLE test1 AS
SELECT Name, Age, Gender, '' AS Occupation
FROM test;

The above simply places empty string as the value for the new occupation column. If you want some other value, then you would need to provide logic for how to populate it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading