Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming Columns in an SQL SELECT Statement

Tags:

sql

mysql

I would like to rename the columns in the results of a SELECT expression. Of course, the following doesn't work:

SELECT * AS foobar_* FROM `foobar` 

As I'm new to SQL, I think I'm just missing a concept, tool, or keyword that would lead to the answer. A hint in the right direction would be appreciated. Thanks!

UPDATE

I'm looking for a generic way to do this, and MySQL-specific techniques are absolutely fine.

In short, I'm writing a tool that "exports" the results of MySQL queries to Google Spreadsheets (via the Google Data API). Some queries are joins, so to make columns unique I wanted to prefix all column names with their respective table names.

like image 944
slackwing Avatar asked Aug 21 '12 10:08

slackwing


People also ask

How do I rename a column in SQL Select?

Use SQL Server Management StudioIn Object Explorer, right-click the table in which you want to rename columns and choose Rename. Type a new column name.

How do I change the column name in output?

1. Renaming a column name using the ALTER keyword. Line 2: RENAME COLUMN OldColumnName TO NewColumnName; For Example: Write a query to rename the column name “SID” to “StudentsID”.


2 Answers

You can alias the column names one by one, like so

SELECT col1 as `MyNameForCol1`, col2 as `MyNameForCol2`  FROM `foobar` 

Edit You can access INFORMATION_SCHEMA.COLUMNS directly to mangle a new alias like so. However, how you fit this into a query is beyond my MySql skills :(

select CONCAT('Foobar_', COLUMN_NAME) from INFORMATION_SCHEMA.COLUMNS  where TABLE_NAME = 'Foobar' 
like image 53
StuartLC Avatar answered Oct 12 '22 21:10

StuartLC


you have to rename each column

SELECT col1 as MyCol1,        col2 as MyCol2,  .......  FROM `foobar` 
like image 36
Joe G Joseph Avatar answered Oct 12 '22 19:10

Joe G Joseph