If there’s one word you will write thousands of times in your career as a developer, it’s SELECT.
The SELECT statement is the fundamental command of the SQL language (and by extension, of T-SQL). Its function is basic but essential: retrieve data from the database.
With it, we can select specific columns, filter rows, sort results, and perform advanced operations on the data.
No matter how well-structured, beautiful, and full of data your database is; if you don’t know how to ask it what you need, it’s basically useless.
Basic Syntax
The most elementary form of a query has two parts:
SELECT columnas
FROM tabla;
- SELECT: Indicates which columns we want to see
- FROM: Indicates from which table we want to get the data
For example,
SELECT Nombre, Apellido
FROM Empleados;
When we execute this, SQL Server goes to the Empleados table, takes all the rows, and returns a result set that only contains the Nombre and Apellido columns.
Selecting All Columns SELECT *
You will often see (and use) the asterisk *. This is a wildcard that means “give me all columns”.
SELECT * FROM Empleados;
This will return all columns from Empleados
Using Aliases AS
Sometimes, column names in the database are technical or cryptic (e.g., Emp_F_Nac). When presenting data, we want it to be readable. For this, we use Aliases.
The keyword is AS.
SELECT
Nombre,
Apellido,
FechaNacimiento AS [Fecha de Nacimiento], -- Alias with spaces
Email AS Correo
FROM Empleados;
This doesn’t change anything in the database, it only changes the column header in the result set we receive.
Calculated Columns
We are not limited to retrieving data exactly as it’s stored. We can perform mathematical operations or text manipulations “on the fly” within the SELECT itself.
Imagine we have a products table with price without VAT.
SELECT
ProductoID,
Nombre,
Precio AS PrecioBase,
Precio * 0.21 AS IVA, -- Calculate the tax
Precio * 1.21 AS PrecioFinal -- Calculate the total
FROM Productos;
We can also join several text columns into one. In T-SQL we use the + operator.
SELECT
Nombre + ' ' + Apellido AS NombreCompleto
FROM Empleados;
Note on Nulls: If you try to add text with a NULL using +, the result will be NULL. To avoid this, we usually use the ISNULL() or CONCAT() function, which we’ll see later in the section on functions.
Removing Duplicates DISTINCT
Sometimes our query returns identical rows and we are only interested in knowing the unique values.
Imagine you want to know in which cities you have customers. If you do a SELECT Ciudad FROM Clientes, “Madrid” will appear 500 times if you have 500 customers there.
To get a clean list, we use DISTINCT.
SELECT DISTINCT Ciudad
FROM Clientes;
This reviews the result and removes duplicate rows, leaving us with only one occurrence per unique value. We can also combine it with several columns:
-- Returns unique combinations of City and Country
SELECT DISTINCT Ciudad, Pais
FROM Clientes;
