r/learnSQL • u/FitShock5083 • Apr 02 '26
Quick Syntax Question
Hi again all! I'm making great progress learning SQL! Quick question: I know you can't reference an alias within the same select clause, so I found an example of code and understand 95% of it, but am stumped by one part. The code is
SELECT subtotal, subtotal * 0.1 AS tax
FROM (SELECT price * quantity AS subtotal FROM sales) AS t;
What is the t doing? I know the code creates a new "field" called subtotal by multiplying price * qty in the inner select clause and that the outer select clause references that new "field" to output a 2 columm dataset with a subtotal column and a tax column, but it kind of seems like, based on the syntax rules, that a third column named t should also be output, but it isn't. What does the AS t; at the end of the code do?
6
Upvotes
View all comments
Show parent comment
2
u/ComicOzzy Apr 03 '26
Not exactly... Let's take a look at your FROM clause:
The FROM clause can refer to TABLEs, VIEWs, and DERIVED TABLEs.
A subquery used this way in the FROM clause is a derived table. The FROM clause will treat it the same way it treats a table, but it needs every table to have a name or it doesn't know what to call it. You've assigned it the name of
t. The subquery returns 1 column namedsubtotalwhich is the result ofprice * quantity.Now let's take a look at your SELECT list:
What SELECT now has access to is a table that has 1 column:
subtotal. BTW, SELECT doesn't care whether it's a real table, a view, or a derived table, it's all the same table-shaped object to SELECT.But in the SELECT list, you output
subtotal, plus an expressionsubtotal * 0.1which you've namedtax.So, the subquery is not returning two columns, but your overall query is returning two columns.