Select Clause
The SELECT clause is one of the most fundamental and frequently used components of SQL. It allows you to retrieve data from one or more tables in a database.
Basic Syntax
The basic syntax of the SELECT statement is:
SELECT column1, column2, ...
FROM table_name;
Examples
1. Selecting All Columns
To select all columns from a table, use the asterisk (*):
SELECT *
FROM employees;
This query retrieves all columns and all rows from the employees
table.
2. Selecting Specific Columns
To select only specific columns:
SELECT first_name, last_name, email
FROM employees;
This query retrieves only the first_name
, last_name
, and email
columns from the employees
table.
3. Using Aliases
You can use aliases to give columns or tables different names in the result set:
SELECT
first_name AS "First Name",
last_name AS "Last Name",
salary * 12 AS "Annual Salary"
FROM employees;
This query renames the columns in the output and calculates an annual salary.
4. Selecting Distinct Values
To select only unique values, use the DISTINCT keyword:
SELECT DISTINCT department
FROM employees;
This query returns a list of unique departments from the employees
table.
5. Using Expressions
You can use expressions in your SELECT statement:
SELECT
product_name,
unit_price,
units_in_stock,
unit_price * units_in_stock AS total_value
FROM products;
This query calculates the total value of each product.
6. Concatenating Columns
In many databases, you can concatenate columns:
SELECT
CONCAT(first_name, ' ', last_name) AS full_name,
email
FROM employees;
This query combines first_name
and last_name
into a single full_name
column.
7. Using Functions
SQL provides various built-in functions that you can use in SELECT statements:
SELECT
COUNT(*) AS total_employees,
AVG(salary) AS average_salary,
MAX(salary) AS highest_salary,
MIN(salary) AS lowest_salary
FROM employees;
This query uses aggregate functions to calculate statistics about employee salaries.
Remember, the SELECT clause is often used in conjunction with other clauses like WHERE, GROUP BY, HAVING, and ORDER BY to create more complex and specific queries.