/

How to Use the SELECT Command in SQL for Data Retrieval

How to Use the SELECT Command in SQL for Data Retrieval

When working with a SQL database, the SELECT command is used to retrieve data from a table. In this blog, we’ll explore how to effectively use the SELECT command to fetch and manipulate data.

Retrieving All Rows and Columns

To retrieve all rows and columns from a table, you can simply use the following query:

1
SELECT * FROM people;

This will return all the rows and columns in the “people” table. Here’s an example of the output:

1
2
3
4
 age | name 
-----+--------
37 | Flavio
8 | Roger

Retrieving Specific Columns

If you only need specific columns from a table, you can specify them in the SELECT statement. For example, to retrieve only the “name” column from the “people” table, use the following query:

1
SELECT name FROM people;

This will return the following result:

1
2
3
4
 name 
--------
Flavio
Roger

Counting Items in a Table

To count the number of items in a table, you can use the COUNT function in conjunction with the SELECT statement. Here’s an example:

1
SELECT COUNT(*) FROM people;

This will provide the following count:

1
2
3
 count 
-------
2

Filtering Rows with the WHERE Clause

The WHERE clause allows you to apply filters to the data you retrieve. For instance, if you only want the “age” for the person named “Flavio,” you can use the following query:

1
SELECT age FROM people WHERE name = 'Flavio';

This will result in:

1
2
3
 age 
-----
37

Sorting Query Results

You can sort the results of your query by a specific column in either ascending or descending order using the ORDER BY clause. For example, to retrieve all rows from the “people” table and sort them by the “name” column in ascending order, use the following query:

1
SELECT * FROM people ORDER BY name;

To sort the results in descending order, use the DESC keyword:

1
SELECT * FROM people ORDER BY name DESC;

These SQL techniques will help you effectively retrieve and manipulate data from your database, providing you with more control over your application.

tags: [“SQL”, “SELECT”, “data retrieval”, “WHERE clause”, “filtering”, “COUNT function”]