Page 34 - SQL
P. 34
So you should always explicitly specify the column(s) you actually want to retrieve:
--SELECT * don't
SELECT ID, FName, LName, PhoneNumber -- do
FROM Emplopees;
(When doing interactive queries, these considerations do not apply.)
However, SELECT * does not hurt in the subquery of an EXISTS operator, because EXISTS ignores
the actual data anyway (it checks only if at least one row has been found). For the same reason, it
is not meaningful to list any specific column(s) for EXISTS, so SELECT * actually makes more
sense:
-- list departments where nobody was hired recently
SELECT ID,
Name
FROM Departments
WHERE NOT EXISTS (SELECT *
FROM Employees
WHERE DepartmentID = Departments.ID
AND HireDate >= '2015-01-01');
Indenting
There is no widely accepted standard. What everyone agrees on is that squeezing everything into
a single line is bad:
SELECT d.Name, COUNT(*) AS Employees FROM Departments AS d JOIN Employees AS e ON d.ID =
e.DepartmentID WHERE d.Name != 'HR' HAVING COUNT(*) > 10 ORDER BY COUNT(*) DESC;
At the minimum, put every clause into a new line, and split lines if they would become too long
otherwise:
SELECT d.Name,
COUNT(*) AS Employees
FROM Departments AS d
JOIN Employees AS e ON d.ID = e.DepartmentID
WHERE d.Name != 'HR'
HAVING COUNT(*) > 10
ORDER BY COUNT(*) DESC;
Sometimes, everything after the SQL keyword introducing a clause is indented to the same
column:
SELECT d.Name,
COUNT(*) AS Employees
FROM Departments AS d
JOIN Employees AS e ON d.ID = e.DepartmentID
WHERE d.Name != 'HR'
HAVING COUNT(*) > 10
ORDER BY COUNT(*) DESC;
https://riptutorial.com/ 16

