Writing Your First SELECT Query
Writing Your First SELECT Query
Now that we have our SQL Server environment set up and a sample database to work with, it's time to start exploring our data. In this post, we'll focus on the most fundamental SQL command: SELECT.
The Heart of SQL: The SELECT Statement
If SQL were a language (which it is!), SELECT would be its most essential verb. This command retrieves data from your database and is the foundation for nearly everything you'll do in SQL.
Think of SELECT as the "show me" command. In Excel, you see all your data immediately when you open a spreadsheet. In SQL, you use SELECT to specify exactly what you want to see.
The Basic SELECT Statement
Let's start with the simplest form of the SELECT statement:
SELECT * FROM Customers;
This command tells SQL Server: "Show me ALL columns (*) FROM the Customers table."
Go ahead and try running this in SQL Server Management Studio (SSMS) against our CoffeeCoDB database. You should see all 30 customer records displayed in a grid format in your results pane, with columns for CustomerID, FirstName, LastName, Email, Phone, and so on.
Breaking Down the Components
Every SELECT statement has at least two parts:
- SELECT - The command itself, telling SQL Server you want to retrieve data
- FROM - Specifies which table to query
In our example:
- - A wildcard meaning "all columns"
- Customers - The name of our target table
- ; - Semicolon to end the statement (optional in SSMS but good practice)
Note: SQL keywords like SELECT and FROM are not case-sensitive, but I'm writing them in uppercase to make them more visible. This is a common convention among SQL developers.
Selecting Specific Columns
While SELECT * is convenient for exploration, it's almost always better to specify exactly which columns you need. This makes your queries more efficient (less data transferred) and your results more focused:
SELECT FirstName, LastName, Email
FROM Customers;
This returns just three columns, making our result set more manageable. When I started with SQL, I got in the habit of always using SELECT * during development (to see what was available), then refining my queries to select only specific columns before finalizing them.
In Excel terms, this is like hiding columns you don't need—except SQL doesn't retrieve the hidden columns at all, making it much more efficient.
Column Order Matters
Unlike Excel, where columns have fixed positions, SQL lets you specify columns in any order you want:
SELECT Email, FirstName, LastName
FROM Customers;
This returns the same data as before, but with the columns rearranged. This is extremely powerful when dealing with tables that have dozens of columns and you need to focus on specific fields.
Readability Matters: Formatting Your Queries
SQL doesn't care about whitespace or line breaks, so you can format your queries to enhance readability. For longer queries, I prefer this style:
SELECT
FirstName,
LastName,
Email,
Country
FROM
Customers;
Placing each column on its own line makes the query easier to read and modify, especially as it grows more complex. This practice also makes version control diffs cleaner if you're storing queries in source control.
Aliasing Columns
Sometimes you'll want to give your columns more readable or descriptive names in the results. This is called "aliasing" and is done with the AS keyword:
SELECT
FirstName AS 'First Name',
LastName AS 'Last Name',
Email AS 'Contact Email'
FROM Customers;
The quotes around the aliases are optional for simple names but necessary if your alias contains spaces or special characters. You can also omit the AS keyword (though I recommend keeping it for clarity):
SELECT
FirstName 'First Name',
LastName 'Last Name',
Email 'Contact Email'
FROM Customers;
In Excel, you'd simply rename a column header. In SQL, aliasing doesn't change the underlying database—it just renames the column in your results.
Calculated Columns
SQL isn't limited to just retrieving stored data. Like Excel formulas, you can perform calculations directly in your SELECT statement:
SELECT
ProductName,
UnitPrice,
UnitsInStock,
UnitPrice * UnitsInStock AS 'Inventory Value'
FROM Products;
This calculates the total value of each product's inventory by multiplying price and quantity. The calculated column exists only in your results—it doesn't modify the database.
Try running this query on our Products table to see which products have the highest inventory value.
SQL Math Operations
SQL supports all standard arithmetic operations:
- + Addition
- Subtraction
- Multiplication
- / Division
For example, to calculate a 10% discount price:
SELECT
ProductName,
UnitPrice,
UnitPrice * 0.9 AS 'Sale Price'
FROM Products;
You can also combine multiple operations:
SELECT
ProductID,
Quantity,
UnitPrice,
Discount,
Quantity * UnitPrice * (1 - Discount) AS 'Line Total'
FROM SalesDetails;
String Concatenation
In Excel, you might use & or CONCATENATE() to join text values. In SQL Server (T-SQL specifically), we use the + operator:
SELECT
FirstName + ' ' + LastName AS 'Full Name',
Email
FROM Customers;
This creates a single column showing each customer's full name.
Dialect Difference Alert: Other SQL dialects handle string concatenation differently:
Using Built-in Functions
SQL Server includes many built-in functions to manipulate data. For example, to convert names to uppercase:
SELECT
UPPER(FirstName) AS 'First Name',
UPPER(LastName) AS 'Last Name',
Email
FROM Customers;
Other useful text functions include:
- LOWER() - Convert to lowercase
- LEN() - Get string length
- SUBSTRING(string, start, length) - Extract part of a string
- LEFT(string, n) - Get n characters from left
- RIGHT(string, n) - Get n characters from right
- TRIM() - Remove spaces from both ends
Date functions are also very useful:
- GETDATE() - Current date and time
- YEAR(date) - Extract year
- MONTH(date) - Extract month
- DAY(date) - Extract day
For example, to see how long customers have been registered:
SELECT
FirstName + ' ' + LastName AS 'Customer',
RegistrationDate,
DATEDIFF(DAY, RegistrationDate, GETDATE()) AS 'Days Registered'
FROM Customers;
Retrieving Distinct Values
Often you'll want to see all the unique values in a column, without duplicates. The DISTINCT keyword handles this:
SELECT DISTINCT Country
FROM Customers;
This shows each country in our Customers table exactly once, regardless of how many customers are from each country.
In Excel, you might use Remove Duplicates or create a PivotTable to achieve this same effect.
DISTINCT with Multiple Columns
You can also use DISTINCT with multiple columns to see unique combinations:
SELECT DISTINCT City, Country
FROM Customers
ORDER BY Country, City;
This shows each unique city/country combination in our database.
Practical Example: Customer Locations
Let's put together a query to analyze where our coffee shop's customers are located:
SELECT
Country,
COUNT(*) AS 'Customer Count',
COUNT(*) * 100.0 / (SELECT COUNT(*) FROM Customers) AS 'Percentage'
FROM
Customers
GROUP BY
Country
ORDER BY
'Customer Count' DESC;
Don't worry about the GROUP BY clause yet—we'll cover that in a future post. For now, notice how we're using calculated columns with a function (COUNT(*)) to get meaningful insights from our data.
Commenting Your SQL
As your queries grow more complex, adding comments becomes important. SQL supports two comment styles:
-- This is a single-line comment
/* This is a
multi-line comment */
SELECT
ProductName,
UnitPrice -- Current retail price
FROM
Products
WHERE
CategoryID = 2; -- Beverages category
Well-commented SQL is easier to understand and maintain, especially when you need to revisit it months later.
SELECT Statement Templates
Here are some templates you can use as starting points for your own queries:
Basic query:
SELECT
Column1,
Column2,
...
FROM
TableName;
Formatted query with aliases:
SELECT
Column1 AS 'Descriptive Name',
Column2 AS 'Another Name',
Column3 * Column4 AS 'Calculated Value'
FROM
TableName;
Common Beginner Pitfalls
As you start writing SELECT queries, watch out for these common issues: