Introduction
The SELECT
statement is fundamental to querying data in SQL Server. It allows you to retrieve data from one or more tables, views, or expressions. Let's explore its syntax and usage through examples.
Syntax
SELECT column1, column2, ...FROM table_nameWHERE condition;
Example 1: Basic SELECT
Retrieve all columns from the "Employees" table.
SELECT *FROM Employees;
Output:
| EmployeeID | FirstName | LastName | Salary ||------------|-----------|----------|--------|| 1 | John | Doe | 50000 || 2 | Jane | Smith | 60000 || 3 | Bob | Johnson | 55000 |
Example 2: Selecting Specific Columns
Retrieve only the "FirstName" and "LastName" columns from the "Employees" table.
SELECT FirstName, LastNameFROM Employees;
Output:
Example 3: Filtering with WHERE
Retrieve employees with a salary greater than 55000.
SELECT *FROM EmployeesWHERE Salary > 55000;Output:| EmployeeID | FirstName | LastName | Salary ||------------|-----------|----------|--------|| 2 | Jane | Smith | 60000 |
Example 4: Aliasing Columns
Use aliases to make the output more readable.
SELECT FirstName AS "First Name", LastName AS "Last Name"FROM Employees;Output:| First Name | Last Name ||------------|-----------|| John | Doe || Jane | Smith || Bob | Johnson |
Example 5: Sorting with ORDER BY
Retrieve employees sorted by salary in descending order.
SELECT *FROM EmployeesORDER BY Salary DESC;Output:| EmployeeID | FirstName | LastName | Salary ||------------|-----------|----------|--------|| 2 | Jane | Smith | 60000 || 3 | Bob | Johnson | 55000 || 1 | John | Doe | 50000 |
Conclusion
The SELECT
statement is a powerful tool for retrieving and manipulating data in SQL Server. This tutorial covered basic usage, column selection, filtering, aliasing, and sorting. As you progress in SQL, you'll discover more advanced features and capabilities of the SELECT
statement.