Data retrieval is one of the most important and frequently used operations in SQL. The SELECT statement is used to fetch data from one or more tables stored in a database. Almost every real-world SQL task involves selecting data, whether it is displaying employee details, generating reports, or filtering job candidates. Understanding the SELECT statement thoroughly is essential for writing effective SQL queries.
The most basic form of data retrieval in SQL is selecting all columns from a table.
SELECT * FROM employees;
In this query:
SELECT tells the database that we want to retrieve data.* represents all columns in the table.FROM employees specifies the table from which the data should be fetched.This query retrieves every column and every row from the employees table. It is commonly used when we want to view all data or quickly inspect the contents of a table.
SELECT * is not recommended in large databases because it retrieves unnecessary data.In real-world applications, we usually need only certain columns instead of all data.
SELECT first_name, last_name, salary
FROM employees;
This query retrieves only the selected columns:
first_namelast_namesalaryBy selecting specific columns:
If an HR manager wants to view only employee names and salaries, selecting unnecessary columns like email or hire date is avoided.
Column aliases are used to rename column headings in the output result for better readability.
SELECT
first_name AS "First Name",
last_name AS "Last Name",
salary AS "Annual Salary"
FROM employees;
AS is used to create an alias (temporary name).This query does not change the actual column names in the database; it only changes how they appear in the result set.
AS keyword, but using it improves claritySometimes a table contains repeated values in a column. To retrieve only unique values, SQL provides the DISTINCT keyword.
SELECT DISTINCT department
FROM employees;
DISTINCT removes duplicate entries.DISTINCT applies to the entire row if multiple columns are selectedSELECT * unnecessarily