Beginner SQL Server

How to Write a SELECT Statement in SQL Server

Learn the fundamentals of querying data with SELECT in SQL Server, including column selection, aliases, and TOP clauses.

5 min read Tutorial

The SELECT statement is the most commonly used command in SQL Server. It retrieves data from one or more tables and is the foundation of every query you will write. In this tutorial, you will learn how to select specific columns, use aliases, retrieve distinct values, and limit results with TOP.

Selecting All Columns

The simplest form of a SELECT statement retrieves every column from a table using the asterisk wildcard. While convenient for exploration, you should avoid SELECT * in production code because it returns unnecessary data and can hurt performance.

SELECT *
FROM Employees;

Selecting Specific Columns

Best practice is to list only the columns you need. This makes your query more readable and efficient.

SELECT FirstName, LastName, Email
FROM Employees;

Column Aliases

Aliases let you rename columns in the result set for clarity. Use the AS keyword or just place the alias after the column name. If the alias contains spaces, wrap it in square brackets.

SELECT
    FirstName AS [First Name],
    LastName AS [Last Name],
    Salary * 12 AS [Annual Salary]
FROM Employees;

Using SELECT TOP

SQL Server uses TOP to limit the number of rows returned, unlike MySQL's LIMIT. You can specify a fixed number or a percentage of rows.

-- Return the first 10 rows
SELECT TOP 10 FirstName, LastName
FROM Employees
ORDER BY HireDate DESC;

-- Return the top 5 percent
SELECT TOP 5 PERCENT *
FROM Orders
ORDER BY OrderTotal DESC;

SELECT DISTINCT

Use DISTINCT to eliminate duplicate rows from your results. This is useful when you need a unique list of values from a column.

SELECT DISTINCT Department
FROM Employees
ORDER BY Department;

Combining Techniques

You can combine these features in a single query. Here is an example that selects specific columns with aliases, removes duplicates, and limits results.

SELECT DISTINCT TOP 20
    e.FirstName + ' ' + e.LastName AS [Full Name],
    d.DepartmentName AS [Department]
FROM Employees e
INNER JOIN Departments d ON e.DepartmentID = d.DepartmentID
ORDER BY [Full Name];

Mastering the SELECT statement gives you a strong foundation for everything else in SQL Server. Practice writing queries that select only the columns you need, use meaningful aliases, and limit results appropriately.

Try this query in UnifySQL

Write, optimize, and collaborate on SQL Server queries with AI assistance.

Start Free