Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to SELECT * and rename a column?

Tags:

sql

mysql

I can easily select all my columns from a table with:

SELECT * FROM foo

But if I want to rename the column bar in foobar, I need to specify all the fields manually. This make my query not robust if a new column is added to the table:

SELECT a,b,c,d,bar AS foobar FROM foo

Is there a possibility to write something like

SELECT *, bar AS foobar from foo
like image 310
nowox Avatar asked Jul 10 '15 13:07

nowox


People also ask

How do I rename a column in select?

Rename Columns with SQL SELECT AS To rename a column use AS. In this example we're renaming FirstName to First and LastName to Last. The AS is optional, can you rewrite the above SQL without using AS?

How do I select and rename a column in R?

To rename a column in R, you can use the rename() function from dplyr. For example, if you want to rename the column “A” to “B” again, you can run the following code: rename(dataframe, B = A) .

How do I rename multiple column names?

To change multiple column names by name and by index use rename() function of the dplyr package and to rename by just name use setnames() from data. table . From R base functionality, we have colnames() and names() functions that can be used to rename a data frame column by a single index or name.


2 Answers

Yes you can do the following:

SELECT  bar AS foobar, a.* from foo as a;

But in this case you will get bar twice: one with name foobar and other with bar as * fetched it..

like image 90
Aman Aggarwal Avatar answered Oct 04 '22 03:10

Aman Aggarwal


There's not really a great way to get at what you're after. Typically, best practices dictate that you should avoid SELECT * ... for performance reasons. Especially for the reason you just specified - say you add a large field to this table that is irrelevant to the query at hand. You're still retrieving the data with a "*" whether you need it or not.

As for your query, you can do SELECT *, bar AS foobar from foo - but you'll be duplicating your results, as you'll return the original column by name as well as a column with your new alias.

Hope this helps!

like image 21
Clayton Donahue Avatar answered Oct 04 '22 03:10

Clayton Donahue