SQL SELECT clause

Syntax

The basic syntax of the SELECT statement is as follows:

SELECT column1, column2, ...
FROM table_name;

Here, table_name refers to the name of the table from which you want to retrieve data. You can specify one or more columns separated by commas in the SELECT clause.

Retrieving all columns

To fetch all columns of a table, you can use the asterisk (*). For example:

SELECT *
FROM employees;

In the above example, the SELECT clause retrieves all columns from the employees table.

Using aliases

You can provide aliases to column names using the AS keyword. Aliases are helpful when you want to rename a column or make the query results more readable. The following example demonstrates alias usage:

SELECT first_name AS "First Name", last_name AS "Last Name"
FROM employees;

In this case, the SELECT clause retrieves the first_name column from the employees table, and renames it as “First Name” in the result set.

Applying filtering conditions

The SELECT clause can be combined with other clauses like WHERE to apply filtering conditions on the retrieved data. The WHERE clause allows you to specify conditions based on which rows are included in the result set. Here’s an example:

SELECT *
FROM employees
WHERE salary > 50000;

This query selects all columns from the employees table where the salary is greater than 50000.

Sorting the result set

You can sort the result set in ascending or descending order using the ORDER BY clause. Here’s an example of sorting the data based on the last_name column:

SELECT *
FROM employees
ORDER BY last_name ASC;

This query retrieves all columns from the employees table and sorts the result set in ascending order of the last_name.

Conclusion

The SELECT clause is a fundamental part of SQL that allows you to retrieve specific columns or all columns from a table. You can apply filtering conditions and sorting to customize the result set according to your requirements. Understanding the syntax and various options available in the SELECT clause is crucial for writing effective SQL queries.

#SQLqueries #database