Execute Program

SQL: Column Aliases

Welcome to the Column Aliases lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • We can rename columns when needed using AS. The result object's properties will use our column aliases instead of the original column names. In this example, we rename the age column, but we leave the name alone.

  • >
    exec(`CREATE TABLE cats (name TEXT, age INTEGER)`);
    exec(`INSERT INTO cats (name, age) VALUES ('Keanu', 2)`);
    exec(`SELECT name, age AS oldness FROM cats`);
    Result:
    [{name: 'Keanu', oldness: 2}]Pass Icon
  • Column aliases become useful in complex queries that involve multiple tables. However, they're also useful for something much simpler: querying mathematical expressions and functions. Now we can clean up the results of those queries!

  • >
    exec(`SELECT 1 + 1`);
    Result:
  • >
    exec(`SELECT 1 + 1 AS sum`);
    Result:
    [{sum: 2}]Pass Icon
  • This lets us avoid retyping complicated expressions:

  • >
    exec(`SELECT DATE('now') > DATE(0)`);
    Result:
  • >
    exec(`SELECT DATE('now') > DATE(0) AS does_the_clock_work`);
    Result:
    [{does_the_clock_work: 1}]Pass Icon
  • Here's a code problem:

    Write a query to retrieve all of the cats. Alias the "name" column to "cat_name" and alias "age" to "cat_age".

    exec(`CREATE TABLE cats (name TEXT, age INTEGER)`);
    exec(`INSERT INTO cats (name, age) VALUES ('Keanu', 2)`);
    exec(`
    SELECT name AS cat_name, age AS cat_age FROM cats
    `);
    Goal:
    [{cat_name: 'Keanu', cat_age: 2}]
    Yours:
    [{cat_name: 'Keanu', cat_age: 2}]Pass Icon