Editor settings

General settings

Save settings

SQL for beginners

Renaming columns with AS #

In SQL, the AS keyword is used to rename a column or a table with an alias in the result set of a query. Renaming columns can improve the readability of the output, provide meaningful names, or alias calculations.

Syntax #

The basic syntax for renaming columns with AS is as follows:

SELECT column_name AS new_name
FROM table_name;

column_name: The original name of the column you want to rename.

new_name: The desired new name for the column.

table_name: The name of the table from which to retrieve the data.

We could rename multiple columns with below syntax:

SELECT
    column_1 AS new_col_1,
    column_2,
    column_3 AS new_col_3
FROM table_name;

In the above example, we rename column_1 to new_col_1 and column_3 to new_col_3 while keeping the column_2 the same. Notice that we can write the command in multiple lines instead of a single line for readability.

Example #

Here's our regular SELECT command:

SELECT first_name, last_name
FROM customers;

Result:

+------------+-----------+
| first_name | last_name |
+------------+-----------+
|   Megan    |   Chang   |
|   .....    |   .....   |

We can rename any of the columns with AS keyword. For example, this command:

SELECT first_name AS name, last_name
FROM customers;

will get you below result:

+----------+-----------+
|   name   | last_name |
+----------+-----------+
|  Megan   |   Chang   |
|  .....   |   .....   |

Exercise #

Write a command that retrieves the data from customers table and rename two columns.

  • Rename column first_name to name.
  • Rename column last_name to lastName.

Expected result

+----------+----------+
|   name   | lastName |
+----------+----------+
|  Megan   |  Chang   |
| Jonathan |  Dixon   |
|  Tammy   |  Howard  |
|   Juan   |  Campos  |
| Vanessa  |  Patel   |
|   Kyle   |  Blair   |
|  Anita   |  Gomez   |
|  Tammy   |  Woods   |
|  Bryan   | Sellers  |
| Jennifer |   Ross   |
+----------+----------+
Solution
SELECT
    first_name AS name,
    last_name AS lastName
FROM
    customers;
Output will be displayed here