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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Database Programming.
Lesson complete
Earn the 3 college credits for Database Programming
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Pulling Data from Multiple Tables: Practical Applications →← 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 →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every credit course with PRO →
Why take it here
Why students take Database Programming with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
Can you use a column alias in a WHERE clause?
Why does a missing comma in a SELECT list not cause an error?
Does a derived table need an alias in SQL?
About the Database Programming course
How many college credits is Database Programming?
How much does Database Programming cost and what is included?
Which universities accept UPI Study credits?
How long does Database Programming take?
How are the exams done?
How do my credits reach my college?
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
3 credits · NCCRSEnroll →