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.
SELECT column1, column2, ...
FROM table_name
WHERE condition;
To retrieve all columns from a table, you can use the * symbol.
SELECT * FROM Employees;
This query retrieves all columns from the Employees table.
You can choose to retrieve only specific columns by listing them.
SELECT FirstName, LastName, HireDate FROM Employees;
This query retrieves only the FirstName, LastName, and HireDate columns from the Employees table.
The WHERE clause is used to filter records based on specific conditions.
SELECT FirstName, LastName FROM Employees WHERE DepartmentID = 101;
This query retrieves only employees from department 101.
Aliases give columns or tables a temporary name.
SELECT FirstName AS "First Name", LastName AS "Last Name" FROM Employees;
This query gives more readable names to the columns in the result set.
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.
DISTINCT is used to return only distinct (different) values in a column.
SELECT DISTINCT DepartmentID FROM Employees;
This query retrieves unique DepartmentID values from the Employees table, avoiding duplicate.