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
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?
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) .
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.
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..
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With