Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select * and make an alias over one column

Tags:

sql

sqlite

Lets imagine a join of 3 tables, it have 14 columns for example. I'd like to rename one of the columns with an alias. Is there some way or doing it without having to write the other 13 column names in the select statement?

What I'm looking in pseudocode is

SELECT * [rename user.login as username] from users join 
        (select * from statistics join accounts)
like image 766
Addev Avatar asked Apr 18 '12 09:04

Addev


People also ask

Can you alias a SELECT statement?

Alias is used to give a temporary name(only for the duration of the query) to the column or table in order to make the column name or table name more readable. It does not change the name of the column permanently.

How do I specify a column alias in SQL?

The basic syntax of a table alias is as follows. SELECT column1, column2.... FROM table_name AS alias_name WHERE [condition];

How do I give an alias to multiple columns in SQL?

Yes, you can alias multiple columns at a time in the same query. It is advisable to always include quotes around the new alias. Quotes are required when the alias contains spaces, punctuation marks, special characters or reserved keywords. It is simply more convenient to always include quotes around the new alias.

What does * mean in SELECT?

An asterisk (" * ") can be used to specify that the query should return all columns of the queried tables. SELECT is the most complex statement in SQL, with optional keywords and clauses that include: The FROM clause, which indicates the table(s) to retrieve data from.


2 Answers

select users.login as username, users.* 
     from users

Unfortunately the column will appear twice, but there's nothing you can do.

With join it will look something like this:

select u.login as username, u.*, s.* 
     from users as u, statistics as s 
     where u.user_id = s.user_id
like image 93
maksimov Avatar answered Sep 22 '22 02:09

maksimov


Your proposed syntax is a good one, IMO. In fact, it is very similar to the database language Tutorial D:

user RENAME ( login AS username )

would project all 14 attributes from the user relvar with one renamed as specified.

Similarly, Tutorial D has an ALL BUT projection operator e.g.

user { ALL BUT login }

would result in a relation of 13 attributes in your case.

Sadly, SQL has never these useful shortcuts and probably never will. Perhaps we should consider ourselves lucky to have got SELECT * in the early days; we would never be granted it in more recent times! The group representing SQL users took a proposal for a SELECT * BUT <commalist> type syntax to the SQL standard committee but it was rejected. SELECT * is disliked on SO too!

like image 45
onedaywhen Avatar answered Sep 22 '22 02:09

onedaywhen