SQL Order of Operations | Ordem das Operações do SQL



Desenvolvido por DORNELLES Carlos Alberto - Analista de Sistemas - Brasília DF. - cad_cobol@hotmail.com

SQL Order of Operations | Ordem das Operações do SQL
  • SQL não é uma linguagem de programação tradicional na qual você escreve uma sequência de instruções em uma determinada ordem de execução.
    Em vez disso, SQL é uma linguagem "declarativa", o que significa que, ao escrever uma consulta SQL, você declara quais dados espera como resultado da consulta, mas não indica como obtê-los.
  • SQL is not a traditional programming language in which you write a sequence of instructions in a given order of execution.
    Instead, SQL is a "declarative" language, which means that by writing a SQL query, you declare what data you expect as a result of the query, but you don't indicate how to obtain it.

Seis operações para ordenar - Six Operations to Order:

SELECT, FROM, WHERE, GROUP BY, HAVING, and ORDER BY

  • Usando exemplos, explicaremos a ordem de execução das seis operações ou partes mais comuns em uma consulta SQL.
    Como o banco de dados executa os componentes de consulta em uma ordem específica, é útil que o desenvolvedor conheça essa ordem.
    É semelhante a seguir uma receita: você precisa saber os ingredientes e o que fazer com os ingredientes, mas também precisa saber em que ordem as tarefas são executadas.
    Se o banco de dados seguir uma ordem diferente de operações, o desempenho da consulta poderá diminuir drasticamente.
  • By using examples, we will explain the execution order of the six most common operations or pieces in an SQL query.
    Because the database executes query components in a specific order, it's helpful for the developer to know this order.
    It's similar to following a recipe: you need to know the ingredients and what to do with ingredients, but you also need to know in which order do the tasks.
    If the database follows a different order of operations, the performance of the query can decrease dramatically.


O banco de dados de funcionários - The Employee Database

  • Neste artigo, trabalharemos com um banco de dados de uma empresa típica que possui funcionários distribuídos em diferentes departamentos.
    Cada funcionário tem um ID, um nome e um salário e pertence a um departamento, como podemos ver nas tabelas a seguir.
  • In this article, we will work with a database for a typical company that has employees distributed in different departments.
    Each employee has an ID, a name, and a salary and belongs to a department, as we can see in the following tables.

Exemplo da tabela EMPLOYEE - Sample of the EMPLOYEE table:

EMPLOYEE_ID FIRST_NAME LAST_NAME SALARY DEPARTMENT
100 James Smith 78,000 ACCOUNTING
101 Mary Sexton 82,000 IT
102 Chun Yen 80,500 ACCOUNTING
103 Agnes Miller 95,000 IT
104 Dmitry Komer 120,000 SALES

Exemplo da tabela DEPARTAMENTO - Sample of the DEPARTMENT table:

DEPT_NAME MANAGER BUDGET
ACCOUNTING 100 300,000
IT 101 250,000
SALES 104 700,000

  • Neste artigo, também usaremos as consultas SQL frequentes utilizadas em uma empresa:
    "Obter os nomes dos funcionários que trabalham para o departamento de TI" ou "Obter o número de funcionários em cada departamento com salário superior a 80.000".
    Para cada uma dessas consultas, analisaremos a ordem de execução de seus componentes.
  • In this article, we will also use frequent SQL queries used in a company:
    "Obtain the names of employees working for the IT department" or "Obtain the number of employees in each department with a salary higher than 80.000."
    For each of these queries, we will analyze the order of execution of its components.



Vamos começar com uma simples consulta para obter os nomes dos funcionários do departamento de TI:

Let's start with a simple query to obtain the names of the employees in the IT department:

     SELECT LAST_NAME
     ,      FIRST_NAME
       FROM EMPLOYEE      WHERE DEPARTMENT = 'IT'

Primeiro, executamos FROM EMPLOYEE , que recupera esses dados:

First, we execute FROM EMPLOYEE, which retrieves this data:

EMPLOYEE_ID FIRST_NAME LAST_NAME SALARY DEPARTMENT
100James Smith 78,000 ACCOUNTING
101Mary Sexton82,000 IT
102Chun Yen 80,500 ACCOUNTING
103Agnes Miller95,000 IT
104DmitryKomer 120,000SALES

Em segundo lugar, executamos WHERE DEPARTMENT = 'IT', o que o reduz a isso:

Second, we execute WHERE DEPARTMENT = 'IT', which narrows it down to this:

EMPLOYEE_ID FIRST_NAME LAST_NAME SALARY DEPARTMENT
101Mary Sexton82,000IT
103AgnesMiller95,000IT

Por fim, aplicamos SELECT FIRST_NAME, LAST_NAME, produzindo o resultado final da consulta:

Finally, we apply SELECT FIRST_NAME, LAST_NAME, producing the final result of the query:

FIRST_NAME LAST_NAME
Mary Sexton
AgnesMiller

Excelente! Depois de concluir nossa primeira dissecação de consultas, podemos concluir que a ordem de execução para consultas simples com SELECT, FROM e WHERE é:

Great! After completing our first query dissection, we can conclude that the order of execution for simple queries with SELECT, FROM, and WHERE is:

Mudanças na Ordem das Operações se Adicionarmos ORDER BY - Changes in the Order of Operations if We Add ORDER BY

  • Suponha que seu chefe receba um relatório com base na consulta do exemplo anterior e o rejeite porque os nomes dos funcionários não estão em ordem alfabética.
    Para corrigi-lo, você precisa adicionar uma cláusula ORDER BY à consulta anterior:
  • Suppose your boss receives a report based on the query in the previous example and rejects it, because the employee names are not in alphabetical order.
    To fix it, you need to add an ORDER BY clause to the previous query:

     SELECT LAST_NAME
     ,      FIRST_NAME
       FROM EMPLOYEE
      WHERE DEPARTMENT = 'IT'
      ORDER BY FIRST_NAME

  • O processo de execução desta consulta é quase o mesmo do exemplo anterior.
    A única alteração é no final, quando a cláusula ORDER BY é processada.
    O resultado final desta consulta ordena as entradas por FIRST_NAME, conforme mostrado abaixo:
  • The execution process of this query is almost the same as in the previous example.
    The only change is at the end, when the ORDER BY clause is processed.
    The final result of this query orders the entries by FIRST_NAME, as shown below:



FIRST_NAME LAST_NAME
AgnesMiller
Mary Sexton

Então, se temos SELECT com FROM, WHERE e ORDER BY, a ordem de execução é:

So, if we have SELECT with FROM, WHERE, and ORDER BY, the order of execution is:

Adicionando cláusulas GROUP BY e HAVING à consulta - Adding GROUP BY and HAVING Clauses to the Query

  • Neste exemplo, usaremos uma consulta com GROUP BY.
    uponha que queremos obter quantos funcionários em cada departamento têm um salário superior a 80.000, e queremos o resultado em ordem decrescente pelo número de pessoas em cada departamento.
    A consulta para esta situação é:
  • In this example, we will use a query with GROUP BY.
    Suppose we want to obtain how many employees in each department have a salary higher than 80,000, and we want the result in descending order by the number of people in each department.
    The query for this situation is:

     SELECT DEPARTMENT
     ,      COUNT(*)
       FROM EMPLOYEES
      WHERE SALARY > 80000
      GROUP BY DEPARTMENT
      ORDER BY COUNT(*) DESC

Novamente, primeiro executamos FROM EMPLOYEE , que recupera esses dados:

Again, we first execute FROM EMPLOYEE, which retrieves this data:

EMPLOYEE_ID FIRST_NAME LAST_NAME SALARY DEPARTMENT
100James Smith 78,000 ACCOUNTING
101Mary Sexton82,000 IT
102Chun Yen 80,500 ACCOUNTING
103Agnes Miller95,000 IT
104DmitryKomer 120,000SALES

Em segundo lugar, executamos WHERE SALARY > 80000, o que o reduz a isso:

Second, we execute WHERE SALARY > 80000, which narrows it down to this:

EMPLOYEE_ID FIRST_NAME LAST_NAME SALARY DEPARTMENT
101Mary Sexton82,000 IT
102Chun Yen 80,500 ACCOUNTING
103Agnes Miller95,000 IT
104DmitryKomer 120,000SALES

Terceiro, GROUP BY é aplicado, gerando um registro para cada valor distinto nas colunas GROUP BY.
Em nosso exemplo, criamos um registro para cada valor distinto em DEPARTMENT:

Third, GROUP BY is applied, generating one record for each distinct value in the GROUP BY columns.
In our example, we create one record for each distinct value in DEPARTMENT:

DEPARTMENT
ACCOUNTING
IT
SALES

Quarto, aplicamos SELECT com COUNT(*), produzindo este resultado intermediário:

Fourth, we apply SELECT with COUNT(*), producing this intermediate result:

DEPARTMENT COUNT(*)
ACCOUNTING1
IT 2
SALES 1

Por fim, aplicamos a cláusula ORDER BY, produzindo o resultado final da consulta:

Finally, we apply the ORDER BY clause, producing the final result of the query:

DEPARTMENT COUNT(*)
IT 2
ACCOUNTING1
SALES 1

A ordem de execução neste exemplo é: - The order of execution in this example is:

  • Neste próximo exemplo, adicionaremos a cláusula HAVING. HAVING não é tão comumente usado em SQL quanto as outras cláusulas que vimos até agora.
    A melhor maneira de descrever HAVING é como a cláusula WHERE para GROUP BY.
    Em outras palavras, é uma forma de filtrar ou descartar alguns dos grupos de registros criados pelo GROUP BY.

    Suponha que agora queremos obter todos os departamentos, exceto o departamento de VENDAS, com um salário médio superior a 80.000.
    A consulta para esta situação é:
  • In this next example, we will add the HAVING clause. HAVING is not as commonly used in SQL as the other clauses we've looked at so far.
    The best way to describe HAVING is that it's like the WHERE clause for GROUP BY.
    In other words, it is a way to filter or discard some of the groups of records created by GROUP BY.

    Suppose we now want to obtain all the departments, except the SALES department, with an average salary higher than 80,000.
    The query for this situation is:

     SELECT DEPARTMENT
       FROM EMPLOYEES
      WHERE DEPARTMENT <> 'SALES'
      GROUP BY DEPARTMENT
     HAVING AVG(SALARY) > 80000

Novamente, primeiro executamos FROM EMPLOYEE , que recupera esses dados:

Again, we first execute FROM EMPLOYEE, which retrieves this data:

EMPLOYEE_ID FIRST_NAME LAST_NAME SALARY DEPARTMENT
100James Smith 78,000ACCOUNTING
101Mary Sexton82,000IT
102Chun Yen 80,500ACCOUNTING
103Agnes Miller95,000IT
104DmitryKomer 120,000SALES

Em segundo lugar, a cláusula WHERE, excluindo os registros SALES, é processada:

Second, the WHERE clause, excluding the SALES records, is processed:

EMPLOYEE_ID FIRST_NAME LAST_NAME SALARY DEPARTMENT
100JamesSmith 78,000ACCOUNTING
101Mary Sexton82,000IT
102Chun Yen 80,500ACCOUNTING
103AgnesMiller95,000IT

Terceiro, aplica-se GROUP BY, gerando os seguintes registros:

Third, GROUP BY is applied, generating the following records:

DEPARTMENT AVG(SALARY)
ACCOUNTING 79,250
IT 88,500

Quarto, HAVING AVG(SALARY) > 80000 é aplicado para filtrar o grupo de registros gerado por GROUP BY:

Fourth, HAVING AVG(SALARY) > 80000 is applied to filter the group of records generated by GROUP BY:

DEPARTMENT AVG(SALARY)
IT 88,500

Por fim, a cláusula SELECT é aplicada, produzindo o resultado final da consulta:

Finally, the SELECT clause is applied, producing the final result of the query:

DEPARTMENT
IT

A ordem de execução neste exemplo é:

The order of execution in this example is:

Adicionando uma nova operação: a cláusula JOIN - Adding a New Operation: The JOIN Clause

  • Os exemplos anteriores trataram de uma tabela. Vamos adicionar uma segunda tabela usando a cláusula JOIN.
    Suponha que queremos obter os sobrenomes e IDs de funcionários de funcionários que trabalham para departamentos com um orçamento superior a 275.000.
    A consulta para esta situação é:
  • The previous examples dealt with one table. Let's add a second table using the JOIN clause.
    Suppose we want to obtain the last names and employee IDs of employees working for departments with a budget higher than 275,000.
    The query for this situation is:

     SELECT EMPLOYEE_ID
     ,      LAST_NAME
       FROM EMPLOYEES
       JOIN DEPARTMENT
         ON DEPARTMENT = DEPT_NAME
      WHERE BUDGET > 275000

Novamente, primeiro executamos FROM EMPLOYEE , que recupera esses dados:

Again, we first execute FROM EMPLOYEE, which retrieves this data:

EMPLOYEE_ID FIRST_NAME LAST_NAME SALARY DEPARTMENT
100James Smith 78,000 ACCOUNTING
101Mary Sexton82,000 IT
102Chun Yen 80,500 ACCOUNTING
103Agnes Miller95,000 IT
104DmitryKomer 120,000SALES

Segundo, aplicamos a cláusula JOIN gerando um novo resultado intermediário combinando as duas tabelas:

Second, we apply the JOIN clause generating a new intermediate result combining both tables:

EMPLOYEE_ID FIRST_NAME LAST_NAME SALARY DEPARTMENT DEPT_NAME MANAGER BUDGET
100James Smith 78,000 ACCOUNTINGACCOUNTING100300,000
101Mary Sexton82,000 IT IT 101250,000
102Chun Yen 80,500 ACCOUNTINGACCOUNTING100300,000
103Agnes Miller95,000 IT IT 101250,000
104DmitryKomer 120,000 SALES SALES 104700,000

Terceiro, WHERE BUDGET > 275.000 é aplicado:

Third, WHERE BUDGET > 275000 is applied:

EMPLOYEE_ID FIRST_NAME LAST_NAME SALARY DEPARTMENT DEPT_NAME MANAGER BUDGET
100James Smith78,000 ACCOUNTINGACCOUNTING 100300,000
102Chun Yen 80,500 ACCOUNTINGACCOUNTING 100300,000
104DmitryKomer120,000SALES SALES 104700,000

Por fim, SELECT EMPLOYEE_ID, LAST_NAME é executado, produzindo o resultado final da consulta:

Finally, SELECT EMPLOYEE_ID, LAST_NAME is executed, producing the final result of the query:

EMPLOYEE_ID LAST_NAME
100Smith
102Yen
104Komer

A ordem de execução neste exemplo é:

The order of execution in this example is:

Palavras de encerramento - Closing Words

  • Neste artigo, abordamos a ordem de execução em consultas SQL por meio de exemplos. A partir desses exemplos, podemos ver que existe uma ordem de execução, mas essa ordem pode variar dependendo de quais cláusulas estão presentes na consulta. Como orientação geral, a ordem de execução é:
  • In this article, we covered the execution order in SQL queries through examples.
    From these examples, we can see that there is an order of execution, but this order may vary depending on which clauses are present in the query.
    As a general guideline, the order of execution is:

No entanto, se uma dessas cláusulas não estiver presente, a ordem de execução será diferente.
SQL é uma linguagem fácil de nível de entrada, mas uma vez que você está dentro, há muitos conceitos brinteressantes para explorar.

However, if one of these clauses is not present, the order of execution will be different.
SQL is an easy, entry-level language, but once you are inside, there are a lot of exciting concepts to explore.


© Copyright LearnSQL.com.