MySQL

Basic Select Queries


In SQL, the SELECT statement is used to retrieve data from one or more tables in a database. The results of a SELECT query are stored in a result set, which is displayed as rows and columns (like a table). Here’s a breakdown of the various ways you can use SELECT queries to manipulate and fetch data.

 

 

Basic Syntax of the SELECT Query

SELECT column1, column2, ...
FROM table_name
WHERE condition;

 

 

 

1. Selecting All Columns

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

Example:

SELECT * FROM Employees;
 

This query retrieves all columns from the Employees table.

 

 

2. Selecting Specific Columns

You can choose to retrieve only specific columns by listing them.

Example:

SELECT FirstName, LastName, HireDate FROM Employees;
 

This query retrieves only the FirstName, LastName, and HireDate columns from the Employees table.

 

 

3. Using WHERE Clause to Filter Data

The WHERE clause is used to filter records based on specific conditions.

Example:

SELECT FirstName, LastName FROM Employees WHERE DepartmentID = 101;
 

This query retrieves only employees from department 101.

 

 

4. Using Aliases for Columns and Tables

Aliases give columns or tables a temporary name.

Example (Column Alias):

SELECT FirstName AS "First Name", LastName AS "Last Name" FROM Employees;

 

This query gives more readable names to the columns in the result set.

 

Example (Table Alias):

SELECT e.FirstName, e.LastName, d.DepartmentName 
FROM Employees AS e
JOIN Departments AS d ON e.DepartmentID = d.DepartmentID;

 

Here, e is used as an alias for the Employees table and d is an alias for the Departments table.

 

 

5. Using DISTINCT to Remove Duplicates

DISTINCT is used to return only distinct (different) values in a column.

Example:

SELECT DISTINCT DepartmentID FROM Employees;
 

This query retrieves unique DepartmentID values from the Employees table, avoiding duplicate.