The SELECT statement is used to retrieve data from one or more tables in a database.

Basic syntax:

SELECT column1, column2, ...
FROM table_name;
  • SELECT → Specifies which columns you want to retrieve.
  • FROM → Specifies the table from which to retrieve the data.

Step 1: Selecting all columns

To retrieve all columns from a table, you use *.

Example:

Assume we have a table Employees:

EmployeeID FirstName LastName Department Salary
1 John Doe IT 5000
2 Jane Smith HR 4500
3 Mike Brown IT 6000
SELECT *
FROM Employees;

Result:

EmployeeID FirstName LastName Department Salary
1 John Doe IT 5000
2 Jane Smith HR 4500
3 Mike Brown IT 6000

* means all columns.

Step 2: Selecting specific columns

You don’t always need all columns. You can select only the ones you need.

SELECT FirstName, LastName, Department
FROM Employees;

Result:

FirstName LastName Department
John Doe IT
Jane Smith HR
Mike Brown IT

Step 3: Using WHERE to filter rows

The WHERE clause allows you to filter data based on conditions.

SELECT *
FROM Employees
WHERE Department = 'IT';

Result:

EmployeeID FirstName LastName Department Salary
1 John Doe IT 5000
3 Mike Brown IT 6000

You can use operators like =, >, <, >=, <=, <> (not equal) and combine conditions with AND / OR.

Step 4: Sorting with ORDER BY

ORDER BY lets you sort the results by one or more columns.

SELECT FirstName, LastName, Salary
FROM Employees
ORDER BY Salary DESC;

Result (sorted by salary descending):

FirstName LastName Salary
Mike Brown 6000
John Doe 5000
Jane Smith 4500

ASC is ascending (default), DESC is descending.

Step 5: Using aliases with AS

You can give columns or tables temporary names using AS.

SELECT FirstName AS Name, Salary AS Income
FROM Employees;

Result:

Name Income
John 5000
Jane 4500
Mike 6000

Step 6: Using TOP to limit rows

TOP allows you to retrieve only a certain number of rows.

SELECT TOP 2 *
FROM Employees
ORDER BY Salary DESC;

Result (top 2 salaries):

EmployeeID FirstName LastName Department Salary
3 Mike Brown IT 6000
1 John Doe IT 5000

Step 7: Using DISTINCT to remove duplicates

DISTINCT removes duplicate values from a column.

SELECT DISTINCT Department
FROM Employees;

Result:

Department
IT
HR

Categorized in:

SQL Server,