Lesson 3 — Querying Data

SELECT Statements

The SELECT statement is the most frequently used command in T-SQL, retrieving rows and columns from one or more tables.

Selecting Columns

You can select specific columns by name, or use * to select every column — though in production code, naming columns explicitly is preferred, since it's clearer and more resilient to future table changes.

T-SQL — SELECT basics
SELECT * FROM Employees;

SELECT FirstName, LastName, HireDate
FROM Employees;

SELECT FirstName AS [First Name], Salary * 12 AS AnnualSalary
FROM Employees;

DISTINCT and TOP

DISTINCT removes duplicate rows from a result set, and TOP limits the number of rows returned — useful for previewing large tables or finding the highest/lowest ranked results when combined with ORDER BY.

T-SQL — DISTINCT and TOP
SELECT DISTINCT Department FROM Employees;

SELECT TOP 5 FirstName, Salary
FROM Employees
ORDER BY Salary DESC;

Common Mistakes

  • Using SELECT * in application code, which can break if columns are later added, removed, or reordered.
  • Forgetting that column aliases created with AS cannot be referenced in the same SELECT's WHERE clause.
  • Assuming TOP without ORDER BY returns a meaningful "top" result — without sorting, the rows returned are arbitrary.
  • Confusing DISTINCT (removes duplicate rows) with GROUP BY, which serves a related but different purpose.

Professional Tip

Always pair TOP with an explicit ORDER BY. SQL Server does not guarantee row order without one, so TOP 5 alone might return a different, arbitrary set of five rows each time the query runs.

Your Turn

Write a query that selects the top 10 highest-paid employees' first name, last name, and salary, aliasing the salary column as AnnualSalary.

Mini Quiz

Why is SELECT * generally discouraged in production application code?