Selected topic

SELECT

Data Query Language Dql

Prefer practical output? Use related tools below while reading.

==========================

The SELECT statement is used to retrieve data from a database table. It's one of the most basic and frequently used queries in SQL.

Basic Syntax:


sql
SELECT column1, column2, ...
FROM tablename;

Explanation:


  • column1, column2, ...: Specify the columns you want to retrieve.
  • FROM tablename;: Specify the table from which to retrieve data.

Example:


Suppose we have a table named employees with the following structure:

| id | name | age | department |
|----|--------|-----|------------|
| 1 | John | 25 | Sales |
| 2 | Jane | 30 | Marketing |
| 3 | Joe | 28 | IT |

To retrieve the name and age of all employees in the Sales department, we can use the following query:

sql
SELECT name, age
FROM employees
WHERE department = 'Sales';

Result:

| name | age | |--------|-----| | John | 25 |

In this example, we used a filter clause (WHERE) to narrow down the results to only those rows where department is 'Sales'.

Variations:


To retrieve all columns from a table, use an asterisk () instead of listing specific columns: SELECT * FROM employees;
  • To sort the results by one or more columns, use the ORDER BY clause: SELECT name, age FROM employees ORDER BY age ASC; (ascends by age)
  • To limit the number of rows retrieved, use the LIMIT clause: SELECT name, age FROM employees LIMIT 2;

Note: This is a basic summary of the SELECT statement. There are many more advanced features and options available in SQL.