Using Aliases to Simplify SQL Queries, Explained

UPI Study › Courses › Database Programming › Free lessons › Lesson 8.6 Free with a free account

Using Aliases to Simplify SQL Queries

Database Programming · Chapter 8: Joining Tables and Combining DataSection 8.6 · lesson 47 of 768 min · free with a free account

← Self-Joins: Joining a Table to ItselfNext lesson: Pulling Data from Multiple Tables: Practical Applications →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

Name tables, columns and derived tables clearly with SQL aliases.

  • Use table aliases to qualify columns and distinguish input roles
  • Give calculated columns readable headings with column aliases and AS
  • Spot the missing-comma mistake that turns a column name into an alias
  • Explain where column aliases can be used in MySQL, SQL Server and SQLite

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,044 words). Read along, or search it.

Opening Problem

A Misleading Last Name Heading

Leo Park develops reports at Lantern Books, our fictional bookstore. An export column says last name, but its values are Asha and Ben. The query ran successfully. A missing comma quietly changed a second column name into an alias, giving Leo a convincing but misleading heading. Temporary names make queries easier to understand when their scope is clear. We will use them deliberately, then expose the mistake behind that export.

Alias Types

Table, Column and Derived-Table Aliases

Restore the canonical bookstore in a disposable database. Its customer and order tables both contain a customer identifier, so qualification will matter. An alias is a temporary name for one query. A table alias names an input role; a column alias names an output value. A derived-table alias names a query result used inside from. These are related naming tools, but they become visible at different logical stages. Run the setup. Our examples execute in SQLite, and we will identify where its permissive behavior differs from MySQL and SQL Server. Aliases do not rename the stored table or alter its schema. The same table can receive a different alias in the following statement.

Table Aliases

Short Names for Input Roles

Give customers the alias c and orders the alias o. The keyword as is optional for these ordinary table aliases, but writing it makes intent clear. Once an input receives an alias, use that alias for its qualified columns. The original table name no longer identifies that input in this scope. A bare customer identifier would be ambiguous because both inputs have it. The prefix c and a dot specify the customer source explicitly. Run the query. Qualifying even unambiguous names can help readers follow data ownership, and avoids surprises when another input gains a same-named column. Asha’s two orders appear with the customer identifier. For a self-join, distinct aliases are essential because both input roles use the same stored column names. Scope still matters. A correlated subquery can refer to an outer alias, but an independently scoped input is not automatically correlated, and inner names can hide outer names.

Column Aliases

Labeling a Calculated Line Total

A column alias gives a calculated result a useful heading. Here quantity times price receives the label line total, instead of an automatic expression heading. Printf formats the result to two decimal places in SQLite. The alias labels that formatted expression; it does not change the underlying product price. Prefer simple identifiers without spaces. A MySQL identifier can use backticks, while SQL Server supports brackets; quoting rules differ between systems. Execute the line report. As is optional for column aliases too, but keeping it explicit distinguishes a label from a separate selected column. The two line totals are twenty-five and nine. They describe item lines, so the order identifier legitimately appears more than once.

Common Mistake

A Missing Comma Creates an Alias

Now reproduce Leo’s export problem. The select list contains first name followed by last name, with no comma between them. Because as is optional, the second identifier becomes a column alias. The statement requests one value with a new heading, rather than two values. This is syntactically valid, so a successful execution cannot catch the mistake. Read both the heading and the kind of values underneath it. Run the export. Compare the heading with the values underneath it, and decide whether they mean what the report promises. Asha and Ben appear under last name. Restore the comma to request both stored fields, or write explicit as when a replacement label is actually intended.

Derived Tables

Naming a Subquery in FROM

A derived table is a query inside from or join, used as an input to the outer query. Here it summarizes orders by customer. The inner column alias order count becomes a column of input t. The outer query can therefore reference t’s column in its own where clause. MySQL and SQL Server require a name for this derived input. SQLite accepts some unnamed forms, but an explicit alias is the portable habit. Run the report for customers with more than one order. Thinking about an inner result is useful, although the optimizer need not physically materialize it first. Asha appears with two orders. The inner result label became available through the outer input, which is different from reusing a sibling select-list alias.

Alias Scope

Where Column Aliases Are Visible

A column alias from select is unavailable in where in MySQL and SQL Server. In the logical model, filtering rows precedes creating output labels. MySQL allows these aliases in group by and having, while SQL Server does not. Those exceptions show why logical order alone cannot replace dialect rules. Both allow output aliases in order by. Neither generally lets a sibling select expression reuse a new alias in that same list. SQLite additionally permits some aliases in where and join conditions. A statement working here therefore does not prove that its naming is portable.

Portable Filter

Repeating the Expression in WHERE

For a portable filter, repeat the expression in where. Reserve line total for the output heading and for order by, where that alias is available. The other repair is to wrap the calculation in a named derived table, then filter its exposed column from the outer query. Repeating the expression does not instruct the server to compute it twice physically. The written form describes meaning; optimization chooses implementation. Run the expression-filter version. It keeps only item lines whose quantity times price exceeds ten, within the selected order. One value remains: twenty-five. The notebook line totals nine and fails the test, while the output alias remains a readable heading.

Quick Check

Filtering a Doubled Score

A new score report doubles six and twelve inside a named derived table. The outer filter keeps doubled values above twenty. Which value does this program return? Pause, and decide.

Answer

Twenty-Four Passes the Outer Filter

Twenty-four is returned. The derived input exposes doubled as a column, so the outer where can filter it by that name. The program confirms twenty-four. Doubling six gives twelve, which fails the outer threshold; doubling twelve gives twenty-four, which passes. Twenty is the boundary, not a computed row value. Naming the derived table makes the scope explicit and keeps the filter portable.

Key Takeaways

Use Each Alias Where It Is Visible

Leo’s misleading export came from a missing comma. Explicit as and a careful select-list review make accidental labels easier to spot. Use table aliases for input roles, column aliases for readable output, and derived aliases for named query inputs. Qualify shared column names. Check where each name is visible. Repeat an expression or expose it through a derived table, when an earlier clause needs to filter it.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Using Aliases to Simplify SQL Queries

What is the difference between a table alias and a column alias in SQL?
A table alias is a temporary name for an input table in one query, while a column alias is a temporary heading for an output value. In SELECT i.quantity * p.price AS line_total FROM order_items AS i JOIN products AS p ON p.product_id = i.product_id, i and p name the inputs and line_total labels the result. Neither renames anything stored, and an aliased table is referenced through its alias.
Can you use a column alias in a WHERE clause?
Not in MySQL or SQL Server, because WHERE is logically evaluated before the SELECT list creates its labels. Both allow the alias in ORDER BY, and MySQL also allows it in GROUP BY and HAVING, while SQL Server does not. SQLite accepts some aliases in WHERE, but that is not portable. Repeat the expression instead, as in WHERE quantity * price > 10, or wrap it in a named derived table.
Why does a missing comma in a SELECT list not cause an error?
Because AS is optional, the second name becomes a column alias for the first. SELECT first_name last_name FROM customers returns one column of first names under the heading last_name, and it runs without any error. Check that each heading matches the kind of values beneath it, restore the comma to request both columns, and write AS explicitly whenever a new label is intended.
Does a derived table need an alias in SQL?
Yes in MySQL and SQL Server: a subquery in FROM must be named, as in SELECT t.customer_id FROM (SELECT customer_id, COUNT(*) AS order_count FROM orders GROUP BY customer_id) AS t WHERE t.order_count > 1. SQLite accepts some unnamed forms, but naming it is the portable habit. The inner alias order_count becomes a column of t, so the outer WHERE can filter on it.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →