Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use aliases in an INSERT statement?

Can we use aliases with insert into syntax?

None of the following work:

INSERT INTO tableblabla AS bla
INSERT INTO bla tableblabla
INSERT INTO tableblabla bla

I can't seem to find any information about this; is there a valid way to use aliases in an INSERT statement?

About the possible reasons: http://bugs.mysql.com/bug.php?id=3275

like image 875
MEM Avatar asked Sep 13 '10 17:09

MEM


People also ask

Can we use alias in SELECT statement?

Table aliases can be used in SELECT lists and in the FROM clause to show the complete record or selective columns from a table. Table aliases can be used in WHERE, GROUP BY, HAVING, and ORDER BY clauses.

What can aliases be used for?

An email alias is an additional email address for an email account, with which a user can send/ receive emails or set forwards to. A single user account can have multiple email aliases, with different domains or even with the same domain. In short, an email alias is like a nick-name or a nick email address.

Can we use case in INSERT statement?

Insert statement with CASEYou can use the CASE expression to insert data into a SQL Server table. The INSERT statement with CASE will scan for the required values and if found, insert values from THEN expression.

Can alias be used without AS?

Yes, you can alias without AS.


1 Answers

Alas, it's not possible as can be seen by the INSERT syntax. Note how it just says [INTO] tbl_name with no mention of [AS] alias, whereas the Update syntax, which does allow aliases, says "table_reference" and further documentation states this can expand to table_factor which includes tbl_name [AS] alias.

It's unfortunate because having the ability to use table aliases on INSERTs would be very useful for INSERT ... ON DUPLICATE KEY UPDATE statements. Especially when performing checks on the columns like in this example:

insert into very_long_table_name_that_can_be_modified_one_day_or_during_testing (
    mykey, 
    column1,
    column2,
    column3,
    <column99>
)
select
    mykey, 
    column1,
    column2,
    column3,
    <column99>
from subquery
on duplicate key update 
    column1 = ifnull(values(column1), very_long_table_name_that_can_be_modified_one_day_or_during_testing.column1), 
    column2 = ifnull(values(column2), very_long_table_name_that_can_be_modified_one_day_or_during_testing.column2), 
    column3 = ifnull(values(column3), very_long_table_name_that_can_be_modified_one_day_or_during_testing.column3), 
    <column99>;

If the table name changes, one has to modify lots of lines of code compared to just having an alias at the beginning which is used in the query.

like image 58
cdesnoye Avatar answered Sep 21 '22 14:09

cdesnoye