A database query is a standard language that allows you to fetch data from one or more tables, to add, update or delete them, in a fast and powerful way; generally known as SQL language.
Let’s start with the basic query, which is essentially composed of the following parts:
SELECT <fields or columns of a table> FROM <table or tables> WHERE <condition to be met by the records> ORDER BY <fields> ASC/DESC
With the SELECT reserved word you choose one or more fields or columns that you want to fetch from a table, the symbol * is used to fetch all the columns of a table.
In the FROM reserved word we put the table or set of tables to which the columns we want to bring in the SELECT belong.
In the WHERE clause we indicate the filters, or necessary conditions for the records that we are bringing, for example that they match or not with some necessary comparisons.
And in the ORDER BY reserved word, we put the fields with which we want to sort the results, either in ascending order (ASC) or descending order (DESC).
Let’s see this in an example:
We have the following table of people:
Table name: t_people
ID | name | lastname | person_id | age | gender | incomes |
1 | Mario | Solis | 4.566.332 | 15 | Male | 650.000 |
2 | Mireya | Portilla | 234.322.323 | 16 | Female | 459.000 |
3 | Luz | Pérez | 74.654.323 | 32 | Female | 2.500.000 |
4 | Gonzalo | Navia | 8.643.234 | 23 | Male | 1.300.000 |
5 | Andrés | Ramírez | 6.342.345 | 18 | Male | 800.000 |
In the following query we are going to get the first and last name of the people with ages over 23 years old, of female gender and in ascending alphabetical order by name:
SELECT name, lastname FROM t_people WHERE age>23 AND gender='Female' ORDER BY name ASC
The result of this query would be:
name | lastname | person_id | age | gender | incomes |
Luz | Pérez | 74.654.323 | 32 | Female | 2.500.000 |
Another example of a query could be to find the total income by gender:
SELECT gender, SUM (incomes) as TOTAL_INCOME FROM t_people GROUP BY gender
Whose result would be:
gender | TOTAL_INCOME |
Male | 2.750.000 |
Female | 2.959.000 |
In this case the aggregate function SUM is used to perform a sum over a set of records, and the GROUP BY clause to indicate the field by which the sum operation is grouped.
This is a simple case of query, later in other articles, we will show more complex and powerful queries for the management and extraction of information from databases.
These articles are part of the process of dissemination of knowledge offered by ITSoftware SAS, within its social function of supporting knowledge as part of the development and progress of humanity.