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:

SELECT * FROM people;

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

 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:

SELECT name FROM people;

This will return the following result:

 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:

SELECT COUNT(*) FROM people;

This will provide the following count:

 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:

SELECT age FROM people WHERE name = 'Flavio';

This will result in:

 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:

SELECT * FROM people ORDER BY name;

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

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.