SELECT C.first_name , C.last_name,
SUM(O.total_price) AS TotalAmount
FROM Customer C , Order O
WHERE C.customer_id = O.customer_id
AND C.customer_id = 12345;
This spacing is very bothersome to me.
SQL select statements have up to 6 distinct clauses. They are:
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY
These keywords should standout. The way we make them stand out is align them to the left-most indentation of the query. Everything else is indented from here.
By just applying this rule, our query looks like this:
SELECT C.first_name , C.last_name,
SUM(O.total_price) AS TotalAmount
FROM Customer C , Order O
WHERE C.customer_id = O.customer_id
AND C.customer_id = 12345;
This is already better, but I still don't like how the rest is lined up. I'll fix that in the next example.
We should be explicit with our join types. To be honest, I have no clue what type of join you're actually using there. I would have to look it up, and it may even be database specific. So let's fix our FROM
clause (and pay attention to some other spacing changes I make):
SELECT C.first_name, C.last_name,
SUM(O.total_price) AS TotalAmount
FROM Customer C
INNER JOIN Order O ON O.customer_id = C.customer_id
WHERE C.customer_id = 12345;
Finally, this query is pretty simple, so the following suggestion is somewhat trivial. However, other queries, may not be so simple. And they may be significantly longer. A good habit to get in might be using variables.
DECLARE @CustomerID int;
SET @CustomerID = 12345;
SELECT C.first_name, C.last_name, SUM(O.total_price) AS TotalAmount
FROM Customer C
INNER JOIN Order O ON O.customer_id = C.customer_id
WHERE C.customer_id = @CustomerID;
Inner Join
syntax until somewhere around 10g. What you have there is an Inner, not a Cross, join. \$\endgroup\$