A Comprehensive Resource for Microsoft Technologies

Welcome, your go-to destination for everything related to .NET and Microsoft technologies. With over 10 years of experience in the IT industry, I am excited to share my knowledge and insights on this platform. This blog is dedicated to providing valuable information, tips, and tutorials that are not only relevant to the rapidly evolving IT industry but also essential for individuals working on real-time projects and preparing for interviews

4.1 SELECT statement

 

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_name
WHERE 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, LastName
FROM Employees;

Output:

| FirstName | LastName |
|-----------|----------|
| John      | Doe      |
| Jane      | Smith    |
| Bob       | Johnson  |

Example 3: Filtering with WHERE

Retrieve employees with a salary greater than 55000.

SELECT *
FROM Employees
WHERE 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 Employees
ORDER 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.