<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Nathalia Friederichs</title>
    <description>The latest articles on DEV Community by Nathalia Friederichs (@nathalia_friederichs).</description>
    <link>https://dev.to/nathalia_friederichs</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1138528%2F6b230ae6-2aed-487a-973e-74e125035fc8.jpeg</url>
      <title>DEV Community: Nathalia Friederichs</title>
      <link>https://dev.to/nathalia_friederichs</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/nathalia_friederichs"/>
    <language>en</language>
    <item>
      <title>Manipulating Dates with SQL Server</title>
      <dc:creator>Nathalia Friederichs</dc:creator>
      <pubDate>Tue, 19 Mar 2024 22:43:30 +0000</pubDate>
      <link>https://dev.to/nathalia_friederichs/manipulating-dates-with-sql-server-58jm</link>
      <guid>https://dev.to/nathalia_friederichs/manipulating-dates-with-sql-server-58jm</guid>
      <description>&lt;p&gt;In the world of data management, dates play a crucial role. In software development projects, data analysis, and reporting, the ability to manipulate and understand temporal information is essential. SQL Server, one of the most widely used database management systems, provides a robust set of functions dedicated to date manipulation.&lt;/p&gt;

&lt;p&gt;This article is a comprehensive guide on the various date manipulation functions available in SQL Server, ranging from simple ones like GETDATE() to more advanced ones like DATEADD(), DATEDIFF(), and others. Mastering these functions provides developers and data analysts with a powerful tool to handle complex date-related scenarios.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;DATEADD()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The DATEADD function in SQL Server is used to add or subtract a specified time interval from a specific date. The syntax of the DATEADD function is as follows:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;DATEADD(interval, number, date)&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;interval: is the part of the date to which the number will be added. This interval can be:&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;Year: year, yy, yyyy&lt;/li&gt;
&lt;li&gt;Quarter: quarter, qq, q&lt;/li&gt;
&lt;li&gt;Month: month, mm, m&lt;/li&gt;
&lt;li&gt;Day of year: dayofyear, dy, y&lt;/li&gt;
&lt;li&gt;Day: day, dd, d&lt;/li&gt;
&lt;li&gt;Week: week, wk, ww&lt;/li&gt;
&lt;li&gt;Weekday: weekday, dw&lt;/li&gt;
&lt;li&gt;Hour: hour, hh&lt;/li&gt;
&lt;li&gt;Minute: minute, mi, n&lt;/li&gt;
&lt;li&gt;Second: second, ss, s&lt;/li&gt;
&lt;li&gt;Millisecond: millisecond, ms&lt;/li&gt;
&lt;li&gt;Microsecond: microsecond, mcs&lt;/li&gt;
&lt;li&gt;Nanosecond: nanosecond, ns&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;number: is the number of date parts to be added to the specified date. It can be positive (for addition) or negative (for subtraction).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;date: is the date to which the interval is added.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here are some practical examples of using DATEADD():&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT DATEADD(DAY, 3, '2023-01-01') AS NewDate&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT DATEADD(DAY, -3, '2023-01-01') AS NewDate&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Note that DATEADD() does not modify the original date; it returns a new date value based on the addition or subtraction of the specified interval.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;DATEDIFF()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In SQL Server, the DATEDIFF function is used to calculate the difference between two dates in terms of a specific interval, such as days, months, years, etc. The basic syntax of the function is as follows:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;DATEDIFF(interval, start_date, end_date)&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;interval: is the interval you want to calculate, such as day for day, month for month, year for year, etc.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;start_date: is the initial date used in the calculation.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;end_date: is the final date used in the calculation.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's look at some practical examples:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT DATEDIFF(DAY, '2023-01-01', '2023-01-10') AS DaysDifference&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT DATEDIFF(MONTH, '2023-05-01', '2023-10-01') AS MonthsDifference&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT DATEDIFF(YEAR, '2020-01-01', '2023-01-01') AS YearsDifference&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;It's important to note that the unit of measure for the difference can vary depending on the chosen interval. For example, if you calculate the difference in months, the result will be the number of complete months between the two dates. If you calculate in years, the result will be the number of complete years between the two dates.&lt;/p&gt;

&lt;p&gt;Remember that DATEDIFF() does not modify the original date; it returns a new date value based on the addition or subtraction of the specified interval.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;DATENAME()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The DATENAME() function in SQL Server is used to return a specific part of a date, such as the month name, day of the week, etc. This function always returns a string. The basic syntax of the function is as follows:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;DATENAME(datepart, date)&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;datepart: is the part of the date you want to return, such as year, month, day, etc.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;date: is the date from which you want to extract the specific part.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here are some practical examples for better understanding:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT DATENAME(MONTH, '2023-01-01') AS MonthName;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT DATENAME(WEEKDAY, '2023-01-01') AS DayOfWeekName;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;These commands will return "January" and "Sunday," respectively.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;DATEPART()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The DATEPART() function in SQL Server is used to extract a specific part of a date, such as the year, month, day, hour, minute, etc. This function always returns an integer. The basic syntax of the function is as follows:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;DATEPART(datepart, date)&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;datepart: is the part of the date you want to extract, such as year, month, day, etc.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;date: is the date from which you want to extract the specific part.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's see a practical example of how the DATEPART() function works:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT DATEPART(WEEKDAY, '2023-01-01') AS DayOfWeekNumber;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT DATEPART(QUARTER, '2023-01-01') AS QuarterNumber;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;In this case, the result will be 7 for the day of the week and 1 for the quarter.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;DAY(), MONTH() &amp;amp; YEAR()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In SQL Server, the functions DAY(), MONTH(), and YEAR() are used to extract specific parts of a date. Each of these functions returns a numeric value corresponding to the specific part of the date.&lt;/p&gt;

&lt;p&gt;A practical example of using the DAY() function:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT DAY('2023-01-01')&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;The result will be 1.&lt;/p&gt;

&lt;p&gt;Practical example using the MONTH() function:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT MONTH('2023-02-01')&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The result will be 2.&lt;/p&gt;

&lt;p&gt;Example using the YEAR() function:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT YEAR('2023-01-01')&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The result will be 2023.&lt;/p&gt;

&lt;p&gt;These functions are useful when you need to extract specific information from a date column or a specific date value. For example, when dealing with reports that need to group data by month or year, you can use these functions to extract this information from the date.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GETDATE()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The GETDATE() function in SQL Server is used to obtain the current date and time of the database server's system. This function does not require arguments and returns a value of the datetime type, representing the current date and time in the 'YYYY-MM-DD hh:mm:ss.sss' format.&lt;/p&gt;

&lt;p&gt;The syntax of this function:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT GETDATE() AS CurrentDate&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GETUTCDATE()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The GETUTCDATE() function in SQL Server is similar to the GETDATE() function but returns the current date and time in the UTC (Coordinated Universal Time) format. UTC is a global time standard that does not vary due to factors such as daylight saving time or regional time zones. The use of UTC is common in distributed systems or when dealing with operations that require global consistency in time.&lt;/p&gt;

&lt;p&gt;The syntax of this function:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT GETUTCDATE() AS CurrentDateUTC&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Unlike GETDATE(), which returns the local date and time of the SQL server, GETUTCDATE() provides the date and time relative to the UTC standard. This can be especially useful in distributed systems or environments where having a consistent and global time reference is crucial.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;SYSDATETIME()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The SYSDATETIME() function in SQL Server is used to obtain the current date and time of the system, including fractional second information. It returns a value of the datetime2 type, which is an extension of the datetime type with higher precision, including fractions of a second.&lt;/p&gt;

&lt;p&gt;The syntax for this function:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT SYSDATETIME() AS CurrentDateTime&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The main difference between SYSDATETIME() and GETDATE() is precision. SYSDATETIME() provides a more accurate representation of time, including fractions of a second, which can be useful in situations that require finer temporal resolution.&lt;/p&gt;

&lt;p&gt;Remember that when choosing between SYSDATETIME() and GETDATE(), you should consider the need for temporal precision for your specific case. In many scenarios, the precision provided by SYSDATETIME() may be unnecessary, and GETDATE() may be sufficient.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ISDATE()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The ISDATE() function is used to check if an expression can be converted to a date and time data type. It returns 1 if the expression can be successfully converted to a date and 0 if it cannot. If the expression is null or cannot be converted to a date, the function will also return 0.&lt;br&gt;
The basic syntax:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;ISDATE(expression)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now, let's go through practical examples:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT ISDATE('2023-01-15') AS Result;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT ISDATE('2023-02-30') AS Result;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The result will be 1 for the first example and 0 for the second example.&lt;/p&gt;

&lt;p&gt;In summary, understanding these functions provides developers and data analysts with a solid foundation to effectively manipulate temporal information in SQL Server. The proper application of these functions contributes to robustness, accuracy, and efficiency in handling date-related data in SQL Server database environments. By incorporating these techniques into projects, professionals can significantly improve the quality and usefulness of their solutions, providing a richer and more informed experience for end users.&lt;/p&gt;

</description>
      <category>database</category>
      <category>sql</category>
      <category>programming</category>
      <category>learning</category>
    </item>
    <item>
      <title>Manipulando Datas com SQL Server</title>
      <dc:creator>Nathalia Friederichs</dc:creator>
      <pubDate>Tue, 05 Mar 2024 22:58:24 +0000</pubDate>
      <link>https://dev.to/nathalia_friederichs/manipulando-datas-com-sql-server-42kb</link>
      <guid>https://dev.to/nathalia_friederichs/manipulando-datas-com-sql-server-42kb</guid>
      <description>&lt;p&gt;No mundo da gestão de dados, as datas desempenham um papel crucial. Em projetos de desenvolvimento de software, análise de dados e relatórios, a habilidade de manipular e compreender informações temporais é essencial. O SQL Server, um dos sistemas de gerenciamento de banco de dados mais amplamente utilizados, oferece uma gama robusta de funções dedicadas à manipulação de datas.&lt;/p&gt;

&lt;p&gt;Este artigo é um guia abrangente sobre as diversas funções de manipulação de datas disponíveis no SQL Server, explorando desde as simples, como GETDATE(), até as mais avançadas, como DATEADD(), DATEDIFF(), e outras. A capacidade de dominar essas funções proporciona aos desenvolvedores e analistas de dados uma ferramenta poderosa para lidar com cenários complexos relacionados a datas.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;DATEADD()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A função DATEADD no SQL Server é utilizada para adicionar ou subtrair um intervalo de tempo especificado a partir de uma data específica. A sintaxe da função DATEADD é a seguinte:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;DATEADD(intervalo, número, data)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Onde:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;intervalo: é a parte da data onde o número será adicionado. Esse intervalo pode ser:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Ano: year, yy, yyyy&lt;/li&gt;
&lt;li&gt;Trimestre: quarter, qq, q&lt;/li&gt;
&lt;li&gt;Mês: month, mm, m&lt;/li&gt;
&lt;li&gt;Dia do ano: dayofyear, dy, y&lt;/li&gt;
&lt;li&gt;Dia: day, dd, d &lt;/li&gt;
&lt;li&gt;Semana: week, wk, ww&lt;/li&gt;
&lt;li&gt;Dia da semana: weekday, dw&lt;/li&gt;
&lt;li&gt;Hora: hour, hh &lt;/li&gt;
&lt;li&gt;Minuto: minute, mi, n&lt;/li&gt;
&lt;li&gt;Segundo: second, ss, s&lt;/li&gt;
&lt;li&gt;Milissegundo: millisecond, ms&lt;/li&gt;
&lt;li&gt;Microssegundo: microsecond, mcs&lt;/li&gt;
&lt;li&gt;Nanossegundo: nanosecond, ns&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;número: é o número de partes da data a serem adicionadas à data especificada. Pode ser positivo (para adição) ou negativo (para subtração).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;data: é a data à qual o intervalo é adicionado.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Alguns exemplos práticos de como usar o DATEADD().&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Adição de 3 dias na data escolhida.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;SELECT DATEADD(DAY, 3, '2023-01-01') AS NovaData&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Subtração de 3 dias na data escolhida.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;SELECT DATEADD(DAY, -3, '2023-01-01') AS NovaData&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Lembre-se de que o DATEADD() não modifica a data original, ele retorna um novo valor de data com base na adição ou subtração do intervalo especificado.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;DATEDIFF()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;No SQL Server a função é usada para calcular a diferença entre duas datas em termos de um intervalo específico, como dias, meses, anos, etc. A sintaxe básica da função é a seguinte:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;DATEDIFF(intervalo, data_inicial, data_final)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Onde:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;intervalo: é o intervalo que você deseja calcular, pode ser day para dia, month para mês, year para ano etc.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;data_inicial: data inicial que será usada no cálculo&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;data_final: data final que será usada no cálculo&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Vamos agora para alguns exemplos práticos.&lt;/p&gt;

&lt;p&gt;Diferença entre duas datas em dias&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT DATEDIFF(DAY, '2023-01-01', '2023-01-10') AS DiferencaDias&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Diferença entre dois meses&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT DATEDIFF(MONTH, '2023-05-01', '2023-10-01') AS DiferencaMeses&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Diferença entre dois anos&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT DATEDIFF(YEAR, '2020-01-01', '2023-01-01') AS DiferencaAnos&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;É importante notar que a unidade de medida para a diferença pode variar dependendo do intervalo escolhido. Por exemplo, se você calcular a diferença em meses, o resultado será o número de meses completos entre as duas datas. Se você calcular em anos, o resultado será o número de anos completos entre as duas datas.&lt;/p&gt;

&lt;p&gt;Lembre-se de que o DATEDIFF() não modifica a data original, ele retorna um novo valor de data com base na adição ou subtração do intervalo especificado.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;DATENAME()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;No SQL Server, a função DATENAME() é utilizada para retornar uma parte específica de uma data, como o nome do mês, o nome do dia da semana, etc. Essa função sempre retorna uma string. A sintaxe básica da função é a seguinte:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;DATENAME(datepart, data)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Onde:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;datepart: é a parte da data que você deseja que retorne. Pode ser uma das seguintes opções:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Ano: year, yy, yyyy&lt;/li&gt;
&lt;li&gt;Trimestre: quarter, qq, q&lt;/li&gt;
&lt;li&gt;Mês: month, mm, m&lt;/li&gt;
&lt;li&gt;Dia do ano: dayofyear, dy, y&lt;/li&gt;
&lt;li&gt;Dia: day, dd, d &lt;/li&gt;
&lt;li&gt;Semana: week, wk, ww&lt;/li&gt;
&lt;li&gt;Dia da semana: weekday, dw&lt;/li&gt;
&lt;li&gt;Hora: hour, hh &lt;/li&gt;
&lt;li&gt;Minuto: minute, mi, n&lt;/li&gt;
&lt;li&gt;Segundo: second, ss, s&lt;/li&gt;
&lt;li&gt;Milissegundo: millisecond, ms&lt;/li&gt;
&lt;li&gt;Microssegundo: microsecond, mcs&lt;/li&gt;
&lt;li&gt;Nanossegundo: nanosecond, ns&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;data: é a data da qual você deseja extrair a parte específica.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Alguns exemplos práticos para melhor entendimento.&lt;/p&gt;

&lt;p&gt;Pegar o nome do mês&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT DATENAME(MONTH, '2023-01-01') AS NomeDoMes;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Esse comando retornará: January&lt;/p&gt;

&lt;p&gt;Pegar qual o dia da semana de uma data&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT DATENAME(WEEKDAY, '2023-01-01') AS NomeDoDiaDaSemana;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Esse comando retornará: Sunday&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;DATEPART()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A função DATEPART() no SQL Server é usada para extrair uma parte específica de uma data, como o ano, mês, dia, hora, minuto, etc. Essa função sempre retorna um inteiro. A sintaxe básica da função é a seguinte:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;DATEPART(datepart, data)&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;datepart: é a parte da data que você deseja extrair. Pode ser uma das seguintes opções:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Ano: year, yy, yyyy&lt;/li&gt;
&lt;li&gt;Trimestre: quarter, qq, q&lt;/li&gt;
&lt;li&gt;Mês: month, mm, m&lt;/li&gt;
&lt;li&gt;Dia do ano: dayofyear, dy, y&lt;/li&gt;
&lt;li&gt;Dia: day, dd, d &lt;/li&gt;
&lt;li&gt;Semana: week, wk, ww&lt;/li&gt;
&lt;li&gt;Dia da semana: weekday, dw&lt;/li&gt;
&lt;li&gt;Hora: hour, hh &lt;/li&gt;
&lt;li&gt;Minuto: minute, mi, n&lt;/li&gt;
&lt;li&gt;Segundo: second, ss, s&lt;/li&gt;
&lt;li&gt;Milissegundo: millisecond, ms&lt;/li&gt;
&lt;li&gt;Microssegundo: microsecond, mcs&lt;/li&gt;
&lt;li&gt;Nanossegundo: nanosecond, ns&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;data: é a data da qual você deseja extrair a parte específica&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A seguir veremos um exemplo prático de como a função DATEPART() funciona.&lt;/p&gt;

&lt;p&gt;Pegar qual o dia da semana de uma data&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT DATENAME(WEEKDAY, '2023-01-01') AS NumeroDoDiaDaSemana;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Nesse caso o retorno será: 7&lt;/p&gt;

&lt;p&gt;Pegar qual o trimeste de uma data&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT DATENAME(QUARTER, '2023-01-01') AS NumeroDoTrimestre;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Já nesse caso, o retorno será: 1&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;DAY(), MONTH() &amp;amp; YEAR()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;No SQL Server, as funções DAY(), MONTH(), e YEAR() são utilizadas para extrair partes específicas de uma data. Cada uma dessas funções retorna um valor numérico correspondente à parte específica da data.&lt;/p&gt;

&lt;p&gt;Um exemplo prático do uso da função DAY()&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT DAY('2023-01-01')&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;O retorno será: 1&lt;/p&gt;

&lt;p&gt;Já o exemplo prático do uso da função MONTH()&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT MONTH('2023-02-01')&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;O retorno será: 2&lt;/p&gt;

&lt;p&gt;Já o exemplo para a função YEAR()&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT YEAR('2023-01-01')&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;O retorno será: 2023&lt;/p&gt;

&lt;p&gt;Essas funções são úteis quando você precisa extrair informações específicas de uma coluna de data ou de um valor de data específico. Por exemplo, ao lidar com relatórios que precisam agrupar dados por mês ou ano, você pode usar essas funções para extrair essas informações da data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GETDATE()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A função GETDATE() no SQL Server é utilizada para obter a data e hora atuais do sistema do banco de dados; do servidor. Essa função não requer argumentos e retorna um valor do tipo datetime, representando a data e hora correntes no formato 'YYYY-MM-DD hh:mm:ss.sss'.&lt;/p&gt;

&lt;p&gt;A sintaxe dessa função&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT GETDATE() AS DataAtual&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GETUTCDATE()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A função GETUTCDATE() no SQL Server é semelhante à função GETDATE(), mas retorna a data e hora atuais no formato UTC (Tempo Universal Coordenado). O UTC é um padrão de tempo global que não sofre variação devido a fatores como horário de verão ou fusos horários regionais. O uso do UTC é comum em sistemas distribuídos ou ao lidar com operações que exigem consistência global no tempo.&lt;/p&gt;

&lt;p&gt;A sintaxe dessa função&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT GETUTCDATE() AS DataAtualUTC&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Ao contrário da GETDATE(), que retorna a data e hora locais do servidor SQL, GETUTCDATE() fornece a data e hora em relação ao padrão UTC. Isso pode ser especialmente útil em sistemas distribuídos ou em ambientes onde é crucial ter um ponto de referência de tempo consistente e global.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;SYSDATETIME()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A função SYSDATETIME() no SQL Server é usada para obter a data e hora atuais do sistema, incluindo informações de frações de segundo. Ela retorna um valor do tipo datetime2, que é uma extensão do tipo datetime com uma precisão maior, incluindo frações de segundo&lt;/p&gt;

&lt;p&gt;A sintaxe para essa função&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT SYSDATETIME() AS DataHoraAtual&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;A principal diferença entre SYSDATETIME() e GETDATE() é a precisão. SYSDATETIME() fornece uma representação mais precisa do tempo, incluindo frações de segundo, o que pode ser útil em situações que exigem uma resolução temporal mais fina.&lt;/p&gt;

&lt;p&gt;Lembre-se de que, ao escolher entre SYSDATETIME() e GETDATE(), você deve considerar a necessidade de precisão temporal para o seu caso específico. Em muitos cenários, a precisão fornecida por SYSDATETIME() pode ser desnecessária, e GETDATE() pode ser suficiente.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ISDATE()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A função ISDATE() é utilizada para verificar se uma expressão pode ser convertida para um tipo de dados de data e hora. Ela retorna 1 se a expressão puder ser convertida com sucesso para uma data, e 0 se não puder. Se a expressão for nula ou não puder ser convertida para uma data, a função também retornará 0.&lt;/p&gt;

&lt;p&gt;Sendo sua sintaxe básica&lt;/p&gt;

&lt;p&gt;&lt;code&gt;ISDATE(expressão)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;expressão: é o que você deseja verificar se pode ser convertida para um tipo de dados de data e hora.&lt;/p&gt;

&lt;p&gt;Agora vamos aos exemplos práticos&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT ISDATE('2023-01-15') AS Resultado;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;O resultado será: 1&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT ISDATE('2023-02-30') AS Resultado;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Nesse caso o resultado será: 0&lt;/p&gt;

&lt;p&gt;Em resumo, a compreensão dessas funções oferece aos desenvolvedores e analistas de dados uma base sólida para manipular efetivamente informações temporais no SQL Server. A aplicação adequada dessas funções contribui para a robustez, precisão e eficiência no tratamento de dados relacionados a datas em ambientes de banco de dados SQL Server. &lt;/p&gt;

&lt;p&gt;Ao incorporar essas técnicas em projetos, os profissionais podem melhorar significativamente a qualidade e a utilidade de suas soluções, proporcionando uma experiência mais rica e informada aos usuários finais.&lt;/p&gt;

</description>
      <category>database</category>
      <category>sql</category>
      <category>learning</category>
      <category>programming</category>
    </item>
    <item>
      <title>Setting Up a PostgreSQL Environment in Docker: A Step-By-Step Guide</title>
      <dc:creator>Nathalia Friederichs</dc:creator>
      <pubDate>Mon, 05 Feb 2024 21:01:07 +0000</pubDate>
      <link>https://dev.to/nathalia_friederichs/setting-up-a-postgresql-environment-in-docker-a-step-by-step-guide-5edo</link>
      <guid>https://dev.to/nathalia_friederichs/setting-up-a-postgresql-environment-in-docker-a-step-by-step-guide-5edo</guid>
      <description>&lt;p&gt;Before anything else, let's begin with a brief explanation of what Docker is.&lt;/p&gt;

&lt;p&gt;Docker is an open-source platform that makes it easy to create, distribute, and run applications within containers. Containers are isolated environments that contain everything necessary to run an application, including code, libraries, dependencies, and configurations. They are similar to virtual machines but are lighter and more resource-efficient.&lt;/p&gt;

&lt;p&gt;Some of the key features and concepts related to Docker include:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Images:&lt;/strong&gt; A Docker image is a package that contains everything needed to run an application, including source code, libraries, dependencies, and configurations. Images are used as templates to create containers.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Containers:&lt;/strong&gt; A Docker container is a running instance of an image. They are isolated from each other and from the host machine, making them consistent and predictable in different environments.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Dockerfile:&lt;/strong&gt; It's a configuration file that defines how to build a Docker image. It describes the steps to create the image, specifying what dependencies to install, how to configure the environment, and more.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Docker Hub:&lt;/strong&gt; It's a public and private repository of Docker images maintained by Docker, Inc. You can find ready-to-use images and share your own images on Docker Hub.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Container Orchestration:&lt;/strong&gt; Docker can be used in container orchestration, meaning you can manage clusters of containers to scale applications, load balance, and ensure high availability. Docker Swarm and Kubernetes are two popular tools for this purpose.&lt;/li&gt;
&lt;/ol&gt;




&lt;p&gt;The first step in creating an environment in Docker is to install Docker on your machine. You can do this by visiting the Docker website at &lt;a href="https://www.docker.com/products/docker-desktop/"&gt;https://www.docker.com/products/docker-desktop/&lt;/a&gt; and selecting the download for your operating system.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbdl8x5zoo7zq3ycjjxo6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbdl8x5zoo7zq3ycjjxo6.png" alt="Image description" width="800" height="409"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To choose and find images, you can search on Docker Hub at &lt;a href="https://hub.docker.com/search?q="&gt;https://hub.docker.com/search?q=&lt;/a&gt; for what you need.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frudculcr6kcazrkj0swo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frudculcr6kcazrkj0swo.png" alt="Image description" width="800" height="452"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PostgreSQL&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff87npnvh7ab17yfi6yqr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff87npnvh7ab17yfi6yqr.png" alt="Image description" width="686" height="656"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To create a PostgreSQL environment in Docker, you can follow the steps below.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Download the PostgreSQL Image&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can download the PostgreSQL image from Docker Hub at &lt;a href="https://hub.docker.com/_/postgres/"&gt;https://hub.docker.com/_/postgres/&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;docker pull postgres&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Create a PostgreSQL Container&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now that you have the PostgreSQL image downloaded, you can create a container with the following command:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;docker run --name my-postgres -e POSTGRES_PASSWORD=my_password -d -p 5432:5432 postgres&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;"my-postgres" is the name of the container (you can choose a different name if you prefer).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;"my_password" is the password you want to set for the "postgres" user in PostgreSQL.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The "-d" option runs the container in the background.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The "-p 5432:5432" option maps port 5432 from the container to port 5432 on the host, allowing you to connect to PostgreSQL from the host.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Accessing PostgreSQL&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now that the PostgreSQL container is running, you can access it using pgAdmin. To do this, you will need to download the pgAdmin image from Docker Hub at &lt;a href="https://hub.docker.com/r/dpage/pgadmin4/"&gt;https://hub.docker.com/r/dpage/pgadmin4/&lt;/a&gt; using the following code:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;docker pull dpage/pgadmin4&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Afterward, you need to create a container for running pgAdmin using the code:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;docker run --name test-pgadmin -p 15432:80 -e "PGADMIN_DEFAULT_EMAIL=&lt;a href="mailto:my_email@test.com"&gt;my_email@test.com&lt;/a&gt;" -e "PGADMIN_DEFAULT_PASSWORD=my_password" -d dpage/pgadmin4&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;"test-pgadmin" is the name of the container being created.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The "-p 15432:80" option maps port 15432, which is used for communication with pgAdmin, to port 80.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;"PGADMIN_DEFAULT_EMAIL" will be the login you use to access pgAdmin.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;"PGADMIN_DEFAULT_PASSWORD" will be the password you use to access pgAdmin.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now you can access pgAdmin at &lt;a href="https://localhost:15432"&gt;https://localhost:15432&lt;/a&gt;, and you will see the pgAdmin interface.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsctkyir6ine9nogsf5p1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsctkyir6ine9nogsf5p1.png" alt="Image description" width="800" height="452"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;After logging in with the defined email and password, the main panel will appear.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fggyxctfjiv18xew0gt79.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fggyxctfjiv18xew0gt79.png" alt="Image description" width="800" height="456"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, the only thing left is to create a server to start using PostgreSQL. Follow these steps:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft9pbv52uvnocnnge458f.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft9pbv52uvnocnnge458f.png" alt="Image description" width="800" height="552"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The next step is to name the server.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0tcwke8ewvrx8557lff8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0tcwke8ewvrx8557lff8.png" alt="Image description" width="800" height="601"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F16tma17001i9i0ccsjyw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F16tma17001i9i0ccsjyw.png" alt="Image description" width="800" height="597"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;In the host name/address, put the name host.docker.internal.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In the port, put the port you defined for your PostgreSQL container.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In the username, enter the default user.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In the password field, enter the password you defined, in this case, "my_password."&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By following all these steps, you will have a screen similar to this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4nzjcxk0ez604duw3s7x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4nzjcxk0ez604duw3s7x.png" alt="Image description" width="800" height="453"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You now have a PostgreSQL environment and pgAdmin running in Docker, and you can start creating databases and tables as needed.&lt;/p&gt;




&lt;p&gt;By following the steps in this article, you can quickly create and set up Docker containers for PostgreSQL and pgAdmin, taking advantage of container virtualization for development and testing. This not only simplifies database administration but also makes collaboration and maintenance of consistent development environments easier.&lt;/p&gt;

&lt;p&gt;It's important to mention that when using Docker containers in production environments, it's essential to consider security, performance, and scalability aspects. After all, this approach, while valuable for development, requires careful evaluation and adaptation to meet production demands.&lt;/p&gt;

</description>
      <category>docker</category>
      <category>postgres</category>
      <category>programming</category>
      <category>database</category>
    </item>
    <item>
      <title>Construindo ambiente PostgreSQL no Docker: Guia Passo a Passo</title>
      <dc:creator>Nathalia Friederichs</dc:creator>
      <pubDate>Mon, 29 Jan 2024 21:39:30 +0000</pubDate>
      <link>https://dev.to/nathalia_friederichs/construindo-ambiente-postgresql-no-docker-guia-passo-a-passo-3pa4</link>
      <guid>https://dev.to/nathalia_friederichs/construindo-ambiente-postgresql-no-docker-guia-passo-a-passo-3pa4</guid>
      <description>&lt;p&gt;Antes de qualquer coisa, vamos para uma breve explicação do que é o Docker.&lt;/p&gt;

&lt;p&gt;Docker é uma plataforma de código aberto que facilita a criação, distribuição e execução de aplicativos em containeres. Containeres são ambientes isolados que contêm tudo o que é necessário para executar um aplicativo, incluindo código, bibliotecas, dependências e configurações. Eles são semelhantes a máquinas virtuais, mas são mais leves e eficientes em termos de recursos.&lt;/p&gt;

&lt;p&gt;Algumas das principais características e conceitos relacionados ao Docker incluem:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Imagens:&lt;/strong&gt; Uma imagem Docker é um pacote que contém todo o necessário para executar um aplicativo, incluindo o código-fonte, bibliotecas, dependências e configurações. As imagens são usadas como modelos para criar containeres.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Containeres:&lt;/strong&gt; Um container Docker é uma instância em execução de uma imagem. Eles são isolados uns dos outros e da máquina host, tornando-os consistentes e previsíveis em diferentes ambientes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Dockerfile:&lt;/strong&gt; É um arquivo de configuração que define como construir uma imagem Docker. Ele descreve as etapas para criar a imagem, especificando quais dependências instalar, como configurar o ambiente e muito mais.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Docker Hub:&lt;/strong&gt; É um repositório público e privado de imagens Docker mantido pela Docker, Inc. Você pode encontrar imagens prontas para uso e compartilhar suas próprias imagens no Docker Hub.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Orquestração de containeres:&lt;/strong&gt; O Docker pode ser usado em orquestração de containeres, o que significa que você pode gerenciar clusters de containeres para dimensionar aplicativos, equilibrar a carga e garantir alta disponibilidade. O Docker Swarm e o Kubernetes são duas das ferramentas populares para essa finalidade.&lt;/li&gt;
&lt;/ol&gt;




&lt;p&gt;O primeiro passo para criar um ambiente no Docker é instalar o Docker na máquina. Para isso basta acessar o site do&lt;a href="https://www.docker.com/products/docker-desktop/"&gt; Docker&lt;/a&gt;&lt;br&gt;
e escolher o download para o seu sistema operacional.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdhrjum19vphicdujbdkl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdhrjum19vphicdujbdkl.png" alt="Image description" width="800" height="409"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Para escolher e encontrar imagens, basta procurar no &lt;a href="https://hub.docker.com/search?q="&gt; Docker Hub&lt;/a&gt; o que deseja.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxee70q217bzy21yerzfa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxee70q217bzy21yerzfa.png" alt="Image description" width="800" height="452"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PostgreSQL&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fex0ajycmx5i0lrxemjm6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fex0ajycmx5i0lrxemjm6.png" alt="Image description" width="686" height="656"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Para criar um ambiente PostgreSQL no Docker, você pode seguir os passos abaixo. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Passo 1: Baixe a imagem do PostgreSQL&lt;/strong&gt;&lt;br&gt;
Você pode baixar a imagem do PostgreSQL a partir do &lt;a href="https://hub.docker.com/_/postgres/"&gt; Docker Hub&lt;/a&gt;, dando o comando abaixo.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;docker pull postgres&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Passo 2: Crie um container PostgreSQL&lt;/em&gt;&lt;br&gt;
Agora que você tem a imagem do PostgreSQL baixada, você pode criar um container com a seguinte linha de comando:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;docker run --name meu-postgres -e POSTGRES_PASSWORD=minha_senha -d -p 5432:5432 postgres&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;meu-postgres é o nome do container (você pode escolher um nome diferente se preferir).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;minha_senha é a senha que você deseja definir para o usuário "postgres" no PostgreSQL.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A opção -d inicia o container em segundo plano.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A opção -p 5432:5432 mapeia a porta 5432 do container para a porta 5432 do host, permitindo que você se conecte ao PostgreSQL do host.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Passo 3: Acessando o PostgreSQL&lt;/p&gt;

&lt;p&gt;Agora que o container PostgreSQL está em execução, você pode acessá-lo usando o pgadmin, para isso, precisará baixar a imagem do pgAdmin do &lt;a href="https://hub.docker.com/r/dpage/pgadmin4/"&gt; Docker Hub&lt;/a&gt; utilizando o código:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;docker pull dpage/pgadmin4&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Depois disso é preciso criar um container para a execução do pgadmin. Para isso, basta usar o código:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;docker run --name teste-pgadmin -p 15432:80 -e "PGADMIN_DEFAULT_EMAIL=&lt;a href="mailto:meu_email@teste.com.br"&gt;meu_email@teste.com.br&lt;/a&gt;" -e "PGADMIN_DEFAULT_PASSWORD=minha_senha" -d dpage/pgadmin4&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;name é o nome do container que vai ser criado.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A opção -p 15432:80 mapeia a porta 15432 que acontece a comunicação com o pgAdmin que será mapeada na porta 80.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A opção PGADMIN_DEFAULT_EMAIL será o login que você usará para acessar o pgAdim.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A opção PGADMIN_DEFAULT_PASSWORD será a senha que você usará para acessar o pgadmin.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Agora basta acessar o pgAdmin utilizado o &lt;a href="https://localhost:15432"&gt;https://localhost:15432&lt;/a&gt; e a seguinte tela irá aparecer:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fga33mgtp3m2hbyt54s19.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fga33mgtp3m2hbyt54s19.png" alt="Image description" width="800" height="452"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Após logar com o email e senha definidos, o painel principal irá aparecer.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzu316ndbcpckgyros1ku.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzu316ndbcpckgyros1ku.png" alt="Image description" width="800" height="456"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Agora só falta criar um Server para poder começar a utilizar o PostgreSQL. Para isso basta seguir o passo a passo:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9n1pgvgql17yw4vtyp4w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9n1pgvgql17yw4vtyp4w.png" alt="Image description" width="800" height="552"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;O próximo passo é dar um nome para o servidor.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frjky3hs8rjb145ikpmly.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frjky3hs8rjb145ikpmly.png" alt="Image description" width="800" height="601"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyd5kxjw431svhlyu7bul.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyd5kxjw431svhlyu7bul.png" alt="Image description" width="800" height="593"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;No host name/address colocamos o nome host.docker.internal&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;No port, colocamos a porta que definimos para nosso container postgres&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;No username, informamos o usuário default&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Password colocamos a senha que definimos, no caso, minha_senha&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ao fazer todo esse passo a passo, você terá uma tela parecida com essa:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm26h3zxa92w00mlz1o97.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm26h3zxa92w00mlz1o97.png" alt="Image description" width="800" height="453"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Você agora tem um ambiente PostgreSQL e pgAdmin em execução no Docker e pode começar a criar bancos de dados e tabelas conforme necessário.&lt;/p&gt;




&lt;p&gt;Ao seguir o passo a passo deste artigo, você pode criar e configurar rapidamente containeres Docker para o PostgreSQL e o PgAdmin, aproveitando os benefícios da virtualização de containeres para desenvolvimento e testes. Isso não apenas simplifica a administração do banco de dados, mas também facilita a colaboração e a manutenção de ambientes de desenvolvimento consistentes.&lt;/p&gt;

&lt;p&gt;É importante mencionar que, ao usar containeres Docker em ambientes de produção, é essencial considerar aspectos de segurança, desempenho e escalabilidade. Afinal, essa abordagem, embora valiosa para o desenvolvimento, requer uma avaliação cuidadosa e adaptação para atender às demandas de produção.&lt;/p&gt;

</description>
      <category>postgres</category>
      <category>docker</category>
      <category>programming</category>
      <category>database</category>
    </item>
    <item>
      <title>Mastering SQL Aggregate Functions: SUM, MAX, MIN, AVG</title>
      <dc:creator>Nathalia Friederichs</dc:creator>
      <pubDate>Mon, 22 Jan 2024 22:14:15 +0000</pubDate>
      <link>https://dev.to/nathalia_friederichs/mastering-sql-aggregate-functions-sum-max-min-avg-3ga</link>
      <guid>https://dev.to/nathalia_friederichs/mastering-sql-aggregate-functions-sum-max-min-avg-3ga</guid>
      <description>&lt;p&gt;In this article, we will discuss some aggregate functions in SQL. These functions are used to perform calculations on specific sets of records in a table.&lt;/p&gt;

&lt;p&gt;For the examples in this article, we will use the following table as a reference.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4imhikspp9izka959pz0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4imhikspp9izka959pz0.png" alt="Image description" width="800" height="343"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To create this table, we used the following commands.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TABLE SALES(ID_SALES INT
                  ,ID_PRODUCET INT
                  ,PRODUCT_NAME VARCHAR(255)
                  ,PRODUCT_PRICE DECIMAL(10, 2)
                  ,SALE_DATE DATE
                  ,SALE_COUNT INT)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;INSERT INTO SALES (ID_SALE
                  ,ID_PRODUCT
                  ,PRODUCT_NAME
                  ,PRODUCT_PRICE
                  ,SALE_DATE
                  ,SALE_COUNT)
VALUES
(1, 100, 'Boots', 79.99, '2023–10–01', 5),
(2, 101, 'T-shirt', 19.99, '2023–10–01', 3),
(3, 300, 'Sneakers', 49.99, '2023–10–01', 2),
(4, 400, 'Bike', 349.99, '2023–10–03', 1),
(5, 500, 'Boxing Gloves', 29.99, '2023–10–04', 2),
(6, 600, 'Basketball Shirt', 24.99, '2023–10–04', 6),
(7, 402, 'Surfboard', 149.99, '2023–10–05', 1),
(8, 301, 'Racket', 39.99, '2023–10–05', 3),
(9, 900, 'Watch', 69.99, '2023–10–05', 4),
(10, 401, 'Skate', 59.99, '2023–10–06', 2 );
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;SUM&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The SUM function returns the sum of a numerical column in the specified set of records in the table.&lt;/p&gt;

&lt;p&gt;The basic syntax of this function is as follows.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT SUM(COLUMN)
  FROM TABLE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's see a practical example with our sample table. In this example, we are calculating the total quantity of sales made in the store.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT SUM(SALE_COUNT) AS SUM_SALE_COUNT
  FROM SALE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The result we obtain is:&lt;/p&gt;

&lt;p&gt;29&lt;/p&gt;

&lt;p&gt;The SUM function is often used in combination with the GROUP BY clause to calculate sums in distinct groups of records, allowing you to analyze aggregate data based on specific criteria. For example, if we want to see the quantity of items sold on each day, we use the following syntax.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT SALE_DATE, SUM(SALE_COUNT) AS SUM_SALE_COUNT
  FROM SALE
GROUP BY SALE_DATE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The result is:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftqe4dnhklm2ne6hp4zdf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftqe4dnhklm2ne6hp4zdf.png" alt="Image description" width="501" height="326"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;MAX&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The MAX function returns the maximum value in a specific column of a table. It allows you to obtain the highest value present in a data column, which can be useful in various situations, such as finding the highest price in a price list, the highest score in a set of results, and more.&lt;/p&gt;

&lt;p&gt;The basic syntax of this function is as follows.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT MAX(COLUMN)
  FROM TABLE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A practical example of using the MAX function, based on our sample table, is when we want to know which product is the most expensive.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT MAX(PRODUCT_PRICE) AS MAX_PRODUCT_PRICE
  FROM SALE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The result we obtain is as follows:&lt;/p&gt;

&lt;p&gt;349.99&lt;/p&gt;

&lt;p&gt;The MAX function is especially useful when you want to identify the highest value in a dataset or when you need to find the record with the maximum value in a specific column. Additionally, it can be combined with other SQL clauses, such as WHERE and GROUP BY, to obtain more refined or filtered results based on specific criteria.&lt;/p&gt;

&lt;p&gt;For example, we may want to retrieve the best-selling product on a specific day. For this, we use the following script.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT TOP 1 PRODUCT_NAME, MAX(SALE_COUNT) AS MAX(SALE_COUNT)
  FROM SALE
 WHERE SALE_DATE = '2023–10–01'
GROUP BY PRODUCT_NAME
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The result being:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F758aye6gogmhwum51mfu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F758aye6gogmhwum51mfu.png" alt="Image description" width="642" height="129"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;MIN&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The MIN function works similarly to the MAX function, but it returns the lowest value present in a data column.&lt;/p&gt;

&lt;p&gt;The basic syntax of this function is as follows.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT MIN(COLUMN)
  FROM TABLE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A practical example of using the MIN function, based on our sample table, is when we want to know which product is the least expensive.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT MIN(PRODUCT_PRICE) AS MIN_PRODUCT_PRICE
  FROM SALE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And this is the result we obtain.&lt;/p&gt;

&lt;p&gt;19.99&lt;/p&gt;

&lt;p&gt;Just like in the MAX function, we can combine the MIN function with other SQL clauses.&lt;/p&gt;

&lt;p&gt;For example, we may want to retrieve the least sold product on a specific day. For this, we use the following script.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT TOP 1 PRODCUT_NAME, MIN(SALE_COUNT) AS MIN_SALE_COUNT
  FROM SALE
 WHERE SALE_DATE = '2023–10–01'
GROUP BY PRODUCT_NAME
ORDER BY MIN(SALE_COUNT)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With the following result:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9o0oay3wed2kqx8pplmc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9o0oay3wed2kqx8pplmc.png" alt="Image description" width="641" height="130"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AVG&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The AVG function is used to calculate the average of values in a specific numerical column, which is useful in situations where you want to find the average of data, such as calculating price averages, scores, ratings, and more.&lt;/p&gt;

&lt;p&gt;The basic syntax of the AVG function is as follows.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT AVG(COLUMN)
  FROM TABLE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using our sample table, let's look at a scenario where we want to find the average price of products sold.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT AVG(PRODUCT_PRICE * SALE_COUNT) AVG_PRICE
  FROM SALE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The result is as follows.&lt;/p&gt;

&lt;p&gt;178.971&lt;/p&gt;

&lt;p&gt;The AVG function is often used in combination with the GROUP BY clause to calculate averages in distinct groups of records and the WHERE clause to filter data, allowing you to analyze aggregate data based on specific criteria. It is useful for calculating average numerical values in large datasets and is a valuable tool in statistical analysis.&lt;/p&gt;

&lt;p&gt;Let's see an example where we want to know the average selling price per day.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT SALE_DATE, AVG(PRODUCT_PRICE * SALE_COUNT) AS AVG_PRICE
  FROM SALE
GROUP BY SALE_DATE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The result we obtain is as follows.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvx9jrapgcaznajdhbdui.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvx9jrapgcaznajdhbdui.png" alt="Image description" width="558" height="330"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In conclusion, the aggregation functions MIN, MAX, SUM, and AVG in SQL are fundamental features for performing calculations on datasets and obtaining valuable insights from your stored data in databases. Each of these functions plays a distinct role in data analysis and generating relevant statistics.&lt;/p&gt;

&lt;p&gt;Mastering the use of these functions is essential for professionals working with databases, software development, or data analysis and can be a crucial skill in interpreting information and conducting meaningful analyses in an increasingly data-driven world. Therefore, exploring these functions and deepening your SQL knowledge is an important step for those looking to unlock the full potential of their data.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>sql</category>
      <category>database</category>
      <category>learning</category>
    </item>
    <item>
      <title>Explorando Funções de Agregação no SQL: SUM, MAX, MIN, AVG</title>
      <dc:creator>Nathalia Friederichs</dc:creator>
      <pubDate>Mon, 15 Jan 2024 22:20:14 +0000</pubDate>
      <link>https://dev.to/nathalia_friederichs/explorando-funcoes-de-agregacao-no-sql-sum-max-min-avg-2689</link>
      <guid>https://dev.to/nathalia_friederichs/explorando-funcoes-de-agregacao-no-sql-sum-max-min-avg-2689</guid>
      <description>&lt;p&gt;Neste artigo iremos falar sobre algumas funções de agregação do SQL. Essas funções de agregação servem para realizar cálculos em determinados conjuntos de registros da tabela.&lt;/p&gt;

&lt;p&gt;Para os exemplos deste artigo, utilizaremos a seguinte tabela como referência.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--l4bYbcwO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v3i6cx5ziwajovnx52aq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--l4bYbcwO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v3i6cx5ziwajovnx52aq.png" alt="Image description" width="800" height="233"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TABLE VENDAS (
                     ID_VENDAS            INT IDENTITY(1, 1) PRIMARY KEY
                    ,ID_PRODUTO           INT
                    ,NOME_PRODUTO         VARCHAR(255)
                    ,PRECO_PRODUTO        DECIMAL(10, 2)
                    ,DATA_VENDA           DATE
                    ,QUANTIDADE_VENDIDA   INT
                    );
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;INSERT INTO VENDAS
 (100, 'Chuteira de Futebol', 79.99, '2023-10-01', 5)
,(101, 'Bola de Futebol', 19.99, '2023-10-01', 3)
,(300, 'Raquete de Tênis', 49.99, '2023-10-01', 2)
,(400, 'Bicicleta Mountain Bike', 349.99, '2023-10-03', 1)
,(500, 'Luvas de Boxe', 29.99, '2023-10-04', 2)
,(600, 'Camisa de Basquete', 24.99, '2023-10-04', 6)
,(402, 'Prancha de Surf', 149.99, '2023-10-05', 1)
,(301, 'Raquete de Squash', 39.99, '2023-10-06', 3)
,(900, 'Tênis de Corrida', 69.99, '2023-10-06', 4)
,(401, 'Skate Completo', 59.99, '2023-10-06', 2)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;SUM&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A função SUM retorna o somatório de uma coluna numérica do determinado conjunto de registros da tabela.&lt;/p&gt;

&lt;p&gt;A sintaxe básica dessa função é a seguinte:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT SUM(COLUNA)
  FROM TABELA
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Vamos ver a seguir um exemplo prático com a nossa tabela de exemplo. Nesse exemplo, estamos pegando a quantidade total das vendas feitas na loja.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT SUM(QUANTIDADE_VENDIDA) AS SOMA_QNT_VENDIDA
  FROM VENDAS
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;O retorno que obtemos é:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--cFa2kOA0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/omekhwawu8bnuxaztrc1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--cFa2kOA0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/omekhwawu8bnuxaztrc1.png" alt="Image description" width="800" height="47"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A função SUM é frequentemente usada em combinação com a cláusula GROUP BY para calcular somas em grupos distintos de registros, permitindo que você analise os dados agregados com base em critérios específicos. Por exemplo, caso queiramos ver a quantidade de itens vendidos em cada dia, fazemos a seguinte sintaxe.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT DATA_VENDA, SUM(QUANTIDADE_VENDIDA) AS SOMA_QNT_VENDIDA
  FROM VENDAS
GROUP BY DATA_VENDA
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;O retorno é:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--BcDPctX7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/prboty2rx7obpi9p6n7i.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--BcDPctX7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/prboty2rx7obpi9p6n7i.png" alt="Image description" width="800" height="129"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;MAX&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A função MAX retorna o valor máximo em uma coluna específica de uma tabela. Ela permite que você obtenha o maior valor presente em uma coluna de dados, que pode ser útil em diversas situações, como encontrar o valor mais alto em uma lista de preços, a maior pontuação em um conjunto de resultados, entre outros.&lt;/p&gt;

&lt;p&gt;A sintaxe básica dessa função é a seguinte:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT MAX(COLUNA)
  FROM TABELA
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Um exemplo prático de uso da função MAX, com base em nossa tabela de exemplo, queremos saber qual é o produto mais caro.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT MAX(PRECO_PODUTO) AS MAX_PRECO_PRODUTO
  FROM VENDAS
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;O retorno que obtemos é o seguinte:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--K1o5mbU8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ioqxrqr0iasj7vqaji01.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--K1o5mbU8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ioqxrqr0iasj7vqaji01.png" alt="Image description" width="800" height="49"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A função MAX é especialmente útil quando você deseja identificar o valor mais alto em um conjunto de dados ou quando precisa encontrar o registro com o valor máximo em uma coluna específica. Além disso, ela pode ser combinada com outras cláusulas SQL, como WHERE, GROUP BY, para obter resultados mais refinados ou filtrados com base em critérios específicos.&lt;/p&gt;

&lt;p&gt;Por exemplo, podemos querer pegar o produto mais vendido em determinado dia. Para isso fazemos o seguinte script.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT TOP 1 NOME_PRODUTO, MAX(QUANTIDADE_VENDIDA) AS MAX_QUANTIDADE_VENDIDA
  FROM VENDAS
 WHERE DATA_VENDA = '2023-10-01'
GROUP BY NOME_PRODUTO 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;O retorno sendo:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--J_ENSQci--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9dr0x2ph7fm32lv73inn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--J_ENSQci--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9dr0x2ph7fm32lv73inn.png" alt="Image description" width="800" height="45"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;MIN&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A função MIN funciona assim como a função MAX, porém ela retorna o menor valor presente em uma coluna de dados.&lt;/p&gt;

&lt;p&gt;A sintaxe básica dessa função é a seguinte:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT MIN(COLUNA)
  FROM TABELA
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Um exemplo prático de uso da função MIN, com base em nossa tabela de exemplo, queremos saber qual é o produto mais barato.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT MIN(PRECO_PRODUTO) AS MIN_PRECO_PRODUTO
  FROM VENDAS
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;E assim obtemos o retorno:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--UUxr-e1j--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4jgfl4bs5lx5veips4b3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--UUxr-e1j--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4jgfl4bs5lx5veips4b3.png" alt="Image description" width="800" height="41"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;E também, assim como na função MAX, podemos combinar a função MIN com outras cláusulas do SQL.&lt;/p&gt;

&lt;p&gt;Por exemplo, podemos querer pegar o produto menos vendido em determinado dia. Para isso fazemos o seguinte script.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT TOP 1 NOME_PRODUTO, MIN(QUANTIDADE_VENDIDA) AS MIN_QUANTIDADE_VENDIDA
  FROM VENDAS
WHERE DATA_VENDA = '2023-10-01'
GROUP BY NOME_PRODUTO
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Com retorno:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--MSCBiEjJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/727464llkww4ktf48bzf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--MSCBiEjJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/727464llkww4ktf48bzf.png" alt="Image description" width="800" height="42"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AVG&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A função AVG é utilizada para calcular a média dos valores de uma coluna numérica específica. O que é útil em situações em que você deseja encontrar a média de dados, como cálculo de médias de preços, pontuações, classificações, e muito mais.&lt;/p&gt;

&lt;p&gt;A sintaxe básica da função AVG é a seguinte:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT AVG(COLUNA)
  FROM TABELA
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Utilizando nossa tabela de exemplo, veremos agora um caso que queremos saber a média do preço dos produtos vendidos:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT AVG(PRECO_PRODUTO * QUANTIDADE_VENDIDA) MEDIA_PRECO
  FROM VENDAS
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;O retorno sendo:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--c15zFneM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lqmmp2e3sn1dzh3nv3dx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--c15zFneM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lqmmp2e3sn1dzh3nv3dx.png" alt="Image description" width="800" height="40"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A função AVG é frequentemente usada em combinação com a cláusula GROUP BY para calcular médias em grupos distintos de registros, e a cláusula WHERE para filtrar os dados, permitindo que você analise os dados agregados com base em critérios específicos. Ela é útil para calcular médias de valores numéricos em grandes conjuntos de dados e é uma ferramenta valiosa na análise estatística de informações.&lt;br&gt;
Vamos ver um exemplo onde queremos saber a média de preço vendido por dia.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT DATA_VENDA, AVG(PRECO_PRODUTO * QUANTIDADE_VENDIDA) MEDIA_PRECO
  FROM VENDAS
GROUP BY DATA_VENDA
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;O resultado que obtemos é o seguinte:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--gR_q78xH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9xe197h1im95ogw83b5v.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--gR_q78xH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9xe197h1im95ogw83b5v.png" alt="Image description" width="800" height="117"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Em conclusão, as funções de agregação MIN, MAX, SUM e AVG no SQL são recursos fundamentais para realizar cálculos em conjuntos de dados e obter insights valiosos a partir de suas informações armazenadas em bancos de dados. Cada uma dessas funções desempenha um papel distinto na análise de dados e na geração de estatísticas relevantes. Destacam-se os ponto:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;MIN (Mínimo)&lt;/strong&gt;: A função MIN permite identificar o menor valor em uma coluna numérica, o que é útil para encontrar valores mínimos, como o preço mais baixo de um produto ou a pontuação mais baixa em um conjunto de resultados.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;MAX (Máximo)&lt;/strong&gt;: A função MAX é usada para encontrar o maior valor em uma coluna numérica, sendo valiosa para identificar valores máximos, como o preço mais alto de um produto ou a pontuação mais alta em uma coleção de dados.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;SUM (Soma)&lt;/strong&gt;: A função SUM calcula a soma dos valores em uma coluna numérica, permitindo agregar e totalizar informações, como a receita total de vendas ou a quantidade total de produtos vendidos em um período.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;AVG (Média)&lt;/strong&gt;: A função AVG é empregada para calcular a média dos valores em uma coluna numérica, o que é crucial para avaliar tendências e médias, como a avaliação média de um produto ou a pontuação média de um conjunto de dados.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Dominar o uso dessas funções é fundamental para qualquer profissional que trabalhe com bancos de dados, desenvolvimento de software ou análise de dados, e pode ser uma habilidade crucial na interpretação de informações e na condução de análises significativas em um mundo cada vez mais orientado por dados. Portanto, explorar essas funções e aprofundar seu conhecimento em SQL é um passo importante para aqueles que desejam aproveitar todo o potencial de seus dados.&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>programming</category>
      <category>sql</category>
      <category>database</category>
    </item>
    <item>
      <title>Unveiling the Potential of the COUNT Function in SQL</title>
      <dc:creator>Nathalia Friederichs</dc:creator>
      <pubDate>Wed, 13 Dec 2023 22:03:25 +0000</pubDate>
      <link>https://dev.to/nathalia_friederichs/unveiling-the-potential-of-the-count-function-in-sql-la</link>
      <guid>https://dev.to/nathalia_friederichs/unveiling-the-potential-of-the-count-function-in-sql-la</guid>
      <description>&lt;p&gt;In this article, we will explore in detail the aggregation function COUNT in SQL. &lt;br&gt;
To illustrate its use in various situations, we will refer to a specific table containing the following records:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwi6640czanv1vafdhekx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwi6640czanv1vafdhekx.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The COUNT function is a fundamental tool for determining the number of records in a specific selection that we are performing in a database. This function has various applications and can be used in several ways.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;COUNT(*)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It is an aggregation function that counts the total number of records in a table, regardless of which columns are being considered. This function does not consider any specific criteria, it simply counts all the existing records in the table, without taking into account the value or presence of data in individual columns.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Syntax&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT COUNT(*) AS COUNT
  FROM COLLEGE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Result&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F33siwf2u5edpjqsisznt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F33siwf2u5edpjqsisznt.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;COUNT(COLUMN_NAME)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It is an aggregation function that counts the number of records in a table where the specified column (COLUMN_NAME) is not null. It is useful when you want to determine how many records contain valid information in a specific column.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Syntax&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT COUNT(COURSE) AS COUNT
  FROM COLLEGE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Result&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe0059ywr4zkuk9y4hkpk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe0059ywr4zkuk9y4hkpk.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now let's count how many students we have in each course. For this, we will need the GROUP BY function; it will group all equal values. In this case, we want to group by course and count the students.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Syntax&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT COURSE, COUNT(STUDENT) AS COUNT_STUDENT
  FROM COLLEGE
GROUP BY COURSE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Result&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxakrnqcmu2q9rqd3q2v4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxakrnqcmu2q9rqd3q2v4.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6kfiz1c0l6bakclvlm97.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6kfiz1c0l6bakclvlm97.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;COUNT(1)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There is a misconception about this command, as many people think it counts all the values in the first column. However, this is not true. Any number or character you put in this function will return the same result because the number in parentheses will be the value that the COUNT function assigns to each row of the table and then counts how many times that value appears.&lt;/p&gt;

&lt;p&gt;Here, I'll show you this:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Syntax using 1&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT COUNT(1) AS COUNT
  FROM COLLEGE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Result using 1&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fal6usueaprqbp4b16o4r.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fal6usueaprqbp4b16o4r.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Syntax using -1000&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT COUNT(-1000) AS COUNT
  FROM COLLEGE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Result using -1000&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0txvju191n2cjfbatwz7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0txvju191n2cjfbatwz7.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Syntax using 'TEXT'&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT COUNT('TEXT') AS COUNT
  FROM COLLEGE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Result using 'TEXT'&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxrjjjpbri08jbn2ju4xj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxrjjjpbri08jbn2ju4xj.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;COUNT(DISTINCT COLUMN_NAME)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We use DISTINCT when we want unique, non-repeated records. In our example, a student can be enrolled in more than one course. Therefore, we use COUNT(DISTINCT STUDENT) to find the exact number of enrolled students.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Syntax&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT COUNT(DISTINCT STUDENT) AS COUNT
  FROM COLLEGE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Result&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkgmeozdp2yxik6j146hg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkgmeozdp2yxik6j146hg.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In conclusion, the COUNT aggregation function in SQL is a powerful and versatile tool for counting records in a dataset. It plays a fundamental role in data analysis and the generation of essential statistics. Here are some key points to highlight:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Precise Counting&lt;/strong&gt;: The COUNT function allows you to count the number of records in a table or a subset of records based on specific criteria defined in the WHERE clause. This is useful for obtaining accurate information about the amount of data available in a set.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Versatility&lt;/strong&gt;: It can be applied in various scenarios, from counting customers in a list to tracking transactions in a financial database. Its flexibility makes it possible to handle a variety of use cases.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Data Grouping&lt;/strong&gt;: By using the GROUP BY clause in conjunction with COUNT, you can count records in distinct groups based on specific column values, which is useful for segmented data analysis.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Powerful Decision-Making Tool&lt;/strong&gt;: The ability to count records is essential for data-informed decision making, report generation, and trend analysis. The COUNT function is an invaluable resource for data professionals and analysts.
Performance Efficiency: In many database management systems, the COUNT function is optimized to provide results quickly, even in large datasets.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In summary, the COUNT aggregation function is a central element in the SQL toolkit and plays a crucial role in obtaining quantitative information from databases. Mastering its use is essential for professionals looking to explore, analyze, and interpret data effectively. By harnessing the full potential of the COUNT function, you will be better prepared to make informed decisions based on solid and reliable data.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>database</category>
      <category>sql</category>
      <category>learning</category>
    </item>
    <item>
      <title>Desvendando o Potencial da Função COUNT no SQL</title>
      <dc:creator>Nathalia Friederichs</dc:creator>
      <pubDate>Mon, 04 Dec 2023 23:07:26 +0000</pubDate>
      <link>https://dev.to/nathalia_friederichs/desvendando-o-potencial-da-funcao-count-no-sql-5f4b</link>
      <guid>https://dev.to/nathalia_friederichs/desvendando-o-potencial-da-funcao-count-no-sql-5f4b</guid>
      <description>&lt;p&gt;Neste artigo, exploraremos em detalhes a função de agregação COUNT no SQL. &lt;br&gt;
Para ilustrar seu uso em várias situações, faremos referência a uma tabela específica contendo os seguintes registros:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flxdt3g905j43owwhx8g5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flxdt3g905j43owwhx8g5.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A função COUNT é uma ferramenta fundamental para determinar o número de registros em uma seleção específica que estamos realizando em um banco de dados. Essa função possui várias aplicações e pode ser empregada de diversas maneiras.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;COUNT(*)&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;É uma função de agregação que conta o número total de registros em uma tabela, independentemente de quais colunas estão sendo consideradas. Essa função não considera nenhum critério específico, ela simplesmente conta todos os registros existentes na tabela, sem levar em consideração o valor ou a presença de dados em colunas individuais.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sintaxe&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT COUNT(*) AS COUNT
  FROM FACULDADE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Resultado&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Falvtuv2u6q46nsbtlzwj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Falvtuv2u6q46nsbtlzwj.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;COUNT(NOME_COLUNA)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;É uma função de agregação que conta o número de registros em uma tabela onde a coluna especificada (NOME_COLUNA) não é nula. Ela é útil quando você deseja determinar quantos registros contêm informações válidas em uma coluna específica.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sintaxe&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT COUNT(CURSO) AS COUNT
  FROM FACULDADE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Resultado&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fp5xqw1789f041i7u4y23.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fp5xqw1789f041i7u4y23.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Vamos agora contar quantos alunos temos em cada curso. Para isso precisaremos da função GROUP BY, ela irá agrupar todos os valores iguais, nesse caso, queremos agrupar por curso, e contar os alunos.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sintaxe&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT CURSO, COUNT(ALUNO) AS QUANTIDADE_ALUNO
  FROM FACULDADE
GROUP BY CURSO
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Resultado&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4az6v7uodlzh412n5kia.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4az6v7uodlzh412n5kia.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;COUNT(1)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Há um equívoco quanto a esse comando, já que muitas pessoas acham que ele conta todos os valores da primeira coluna, porém isso não é verdade, qualquer número ou caractere que você colocar nessa função retornará o mesmo resultado, isso porque o número em parênteses será o valor que a função COUNT irá atribuir a cada linha da tabela e depois contará quantas vezes esse valor aparece.&lt;/p&gt;

&lt;p&gt;Aqui te mostro isso:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sintaxe utilizando o 1&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT COUNT(1) AS COUNT
  FROM FACULDADE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Resultado utilizando o 1&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fguzamqv4nxazfypmswen.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fguzamqv4nxazfypmswen.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sintaxe utilizando -1000&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT COUNT(-1000) AS COUNT
  FROM FACULDADE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Resultado utilizando -1000&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3zmnv5eqqa4ocbpxs93k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3zmnv5eqqa4ocbpxs93k.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sintaxe utilizando o 'TEXTO'&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT COUNT('TEXTO') AS COUNT
  FROM FACULDADE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Resultado utilizando o 'TEXTO'&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh5oy6jmnc7ibt8gztdun.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh5oy6jmnc7ibt8gztdun.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;COUNT(DISTINCT NOME_COLUNA)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Utilizamos o DISTINCT quando queremos os registros sem repetição de valor. No nosso exemplo, um aluno pode estar cursando mais de um curso. Sendo assim usamos o COUNT(DISTINCT ALUNO) para saber o número exato de alunos matriculados.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sintaxe&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT COUNT(DISTINCT ALUNO)
  FROM FACULDADE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Resultado&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3jxfgdoa3eotp71tq4ox.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3jxfgdoa3eotp71tq4ox.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Em conclusão, a função de agregação COUNT no SQL é uma ferramenta poderosa e versátil para a contagem de registros em um conjunto de dados. Ela desempenha um papel fundamental na análise de dados e na geração de estatísticas essenciais. Aqui estão alguns pontos-chave a serem destacados:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Contagem Precisa&lt;/strong&gt;: A função COUNT permite contar o número de registros em uma tabela ou em um subconjunto de registros, com base em critérios específicos definidos na cláusula WHERE. Isso é útil para obter informações precisas sobre a quantidade de dados disponíveis em um conjunto.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Versatilidade&lt;/strong&gt;: Pode ser aplicada em diferentes cenários, desde contagem de clientes em uma lista até o acompanhamento de transações em uma base de dados financeira. Sua flexibilidade torna possível lidar com uma variedade de casos de uso.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Agrupamento de Dados&lt;/strong&gt;: Ao usar a cláusula GROUP BY em conjunto com COUNT, é possível contar registros em grupos distintos com base em valores de colunas específicas, o que é útil para análises de dados segmentadas.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Ferramenta Poderosa para Tomada de Decisões&lt;/strong&gt;: A capacidade de contar registros é fundamental para a tomada de decisões informadas, a geração de relatórios e a análise de tendências. A função COUNT é um recurso inestimável para profissionais de dados e analistas.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Eficiência de Desempenho&lt;/strong&gt;: Em muitos sistemas de gerenciamento de banco de dados, a função COUNT é otimizada para fornecer resultados rapidamente, mesmo em grandes conjuntos de dados.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Em resumo, a função de agregação COUNT é um elemento central no arsenal de ferramentas SQL e desempenha um papel crucial na obtenção de informações quantitativas a partir de bancos de dados. Dominar seu uso é fundamental para profissionais que desejam explorar, analisar e interpretar dados de maneira eficaz. Ao aproveitar todo o potencial da função COUNT, você estará melhor preparado para tomar decisões informadas com base em dados sólidos e confiáveis.&lt;/p&gt;

&lt;p&gt;Se você deseja testar esses comandos sem a necessidade de configurar um ambiente, você pode utilizar o site &lt;a href="http://sqlfiddle.com/#!18" rel="noopener noreferrer"&gt;http://sqlfiddle.com/#!18&lt;/a&gt;. Nesse site, você tem a opção de escolher o Sistema de Gerenciamento de Banco de Dados (SGBD) que deseja usar e pode comparar as diferenças entre as sintaxes. Para os exemplos deste artigo, utilizei o MS SQL SERVER 2017.&lt;/p&gt;

</description>
      <category>sql</category>
      <category>database</category>
      <category>learning</category>
      <category>programming</category>
    </item>
    <item>
      <title>Unlock the Power of SQL JOINs: A Comprehensive Guide</title>
      <dc:creator>Nathalia Friederichs</dc:creator>
      <pubDate>Mon, 27 Nov 2023 22:21:56 +0000</pubDate>
      <link>https://dev.to/nathalia_friederichs/unlock-the-power-of-sql-joins-a-comprehensive-guide-4c3m</link>
      <guid>https://dev.to/nathalia_friederichs/unlock-the-power-of-sql-joins-a-comprehensive-guide-4c3m</guid>
      <description>&lt;p&gt;In this article, we will discuss the SQL JOIN command, which is used when there is a need to combine two or more tables. This command is essential when querying information that is distributed across different tables but has some kind of relationship or link.&lt;/p&gt;

&lt;p&gt;There are several approaches to execute this type of join. Some of them are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;INNER JOIN &lt;/li&gt;
&lt;li&gt;LEFT JOIN &lt;/li&gt;
&lt;li&gt;RIGHT JOIN &lt;/li&gt;
&lt;li&gt;FULL OUTER JOIN &lt;/li&gt;
&lt;li&gt;CROSS JOIN&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;INNER JOIN&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Returns only the records that have a match in both tables involved in the join. Records without a match are excluded from the result.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkf3hqwdcqc7s2uicnwm3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkf3hqwdcqc7s2uicnwm3.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The basic syntax for performing a JOIN involves specifying the tables involved and the join conditions, typically defined by the ON clause, where the related fields in the tables are indicated.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fha6aa15y1c2mi4zi7gz4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fha6aa15y1c2mi4zi7gz4.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;LEFT JOIN&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Returns all records from the left table (the first table listed) along with corresponding records from the right table (the second table listed). If there is no match in the right table, the fields associated with that table will contain null values.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyo7unypjf2rwucczo4ie.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyo7unypjf2rwucczo4ie.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To perform this join, we use the following command:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdlil94l5avxau5h1n123.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdlil94l5avxau5h1n123.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can perform the LEFT JOIN excluding the INNER JOIN results, this is called LEFT JOIN EXCLUDING INNER JOIN.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvcjzwm35rxz16gcwpxlt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvcjzwm35rxz16gcwpxlt.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To perform this join, we use the following command:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnvssdd9m7upo4j3hnpds.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnvssdd9m7upo4j3hnpds.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;RIGHT JOIN&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Similar to the LEFT JOIN but returns all records from the right table with their corresponding records from the left table. Records without a match in the left table will result in null values in the associated fields.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fes00vmjnlnmc5vtdy3xh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fes00vmjnlnmc5vtdy3xh.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To perform this join, we use the following command:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F65ipch2bths7gsx9hzz1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F65ipch2bths7gsx9hzz1.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Just like in the LEFT JOIN, we can also exclude results from the INNER JOIN in the RIGHT JOIN, this is called RIGHT JOIN EXCLUDING INNER JOIN.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fek7fg5mnmg4tnxlh79dv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fek7fg5mnmg4tnxlh79dv.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To perform this join, we use the following command:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fimqflq1g92t3yjvest8d.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fimqflq1g92t3yjvest8d.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;FULL OUTER JOIN&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Or simply FULL JOIN, returns all records from both tables, including records that have no match in the opposite table. Fields without a match will contain null values.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvannpcjsxezkpo4cvtsl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvannpcjsxezkpo4cvtsl.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To perform this join, we use the following command:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6zy1p0uga2f8spg16sj4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6zy1p0uga2f8spg16sj4.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;There is also FULL JOIN EXCLUDING INNER JOIN, which is a FULL JOIN excluding the INNER JOIN.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3eyezzs6r5j5irsjov28.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3eyezzs6r5j5irsjov28.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To perform this join, we use the following command:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5f4xx2bjw4vb20ta9lbr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5f4xx2bjw4vb20ta9lbr.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CROSS JOIN&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It is a type of join that combines all rows from two or more tables involved, producing a result set that is the Cartesian product of these tables. This means that each row from the first table will be combined with all rows from the second table and so on, generating all possible combinations.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Syntax&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0apc1rcgva5aw9pfw2h1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0apc1rcgva5aw9pfw2h1.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Note that we don't have the "ON A.KEY = B.KEY" in this case because we're not relating the columns.&lt;/p&gt;

&lt;p&gt;In this example, the query returns all possible combinations between table A and table B. If there are 10 records in table A and 5 records in table B, the result will contain 50 rows, combining each record from table A with all records from table B.&lt;/p&gt;

&lt;p&gt;Generally, CROSS JOIN is not as commonly used as other types of JOINs because in most cases, we are interested in combining records based on specific relationship criteria. However, in some scenarios, it can be useful, such as generating Cartesian combinations or producing specific results in complex reports.&lt;/p&gt;

&lt;p&gt;Below is an image summarizing the most common JOINs.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq9jg3d1nax7pnmasqezk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq9jg3d1nax7pnmasqezk.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In conclusion, JOIN clauses in SQL are an essential part of data manipulation and analysis in relational databases. They allow you to combine data from multiple tables based on key relationships, thereby expanding the ability to extract valuable information from interconnected datasets.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Data Connection&lt;/strong&gt;: JOIN clauses enable you to merge information from different tables, which is crucial for building complex queries that retrieve related data from various sources.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Various Types of JOINs&lt;/strong&gt;: SQL offers different types of joins, such as INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN, each suitable for specific scenarios. This provides flexibility in data retrieval.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Complex Relationships&lt;/strong&gt;: Joins are crucial when dealing with complex databases that have many tables with relationships between them. They help bring clarity and organization to your data.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Data-Driven Decision Making&lt;/strong&gt;: Mastering JOIN clauses is essential for professionals seeking to obtain accurate information from databases, which, in turn, supports data-informed decision making.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In summary, understanding JOIN clauses in SQL is a critical skill for anyone working with data in a relational database environment. Mastering the art of joining and relating tables allows you to extract valuable insights, build complex reports, and ultimately make decisions based on solid data. Therefore, deepening your knowledge of joins is an important step on the journey to becoming an efficient data management and analysis professional.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>sql</category>
      <category>database</category>
      <category>learning</category>
    </item>
    <item>
      <title>Dominando JOINs no SQL: Guia Completo</title>
      <dc:creator>Nathalia Friederichs</dc:creator>
      <pubDate>Mon, 13 Nov 2023 22:39:19 +0000</pubDate>
      <link>https://dev.to/nathalia_friederichs/dominando-joins-no-sql-guia-completo-39m0</link>
      <guid>https://dev.to/nathalia_friederichs/dominando-joins-no-sql-guia-completo-39m0</guid>
      <description>&lt;p&gt;Neste artigo, abordaremos o comando JOIN no SQL, que é empregado quando há a necessidade de combinar duas ou mais tabelas. &lt;/p&gt;

&lt;p&gt;Esse comando é fundamental quando há a necessidade de consultar informações que estejam distribuídas entre tabelas diferentes, mas que possuam algum tipo de relação ou vínculo.&lt;/p&gt;

&lt;p&gt;Existem diversas abordagens para a execução desse tipo de junção. Algumas delas são:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;INNER JOIN&lt;/li&gt;
&lt;li&gt;LEFT JOIN&lt;/li&gt;
&lt;li&gt;RIGHT JOIN&lt;/li&gt;
&lt;li&gt;FULL OUTER JOIN&lt;/li&gt;
&lt;li&gt;CROSS JOIN&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;INNER JOIN&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Retorna apenas os registros que possuem correspondência nas duas tabelas envolvidas na junção. Registros que não possuam correspondência são excluídos do resultado.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2thy0yvxuabxcpvc2hy2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2thy0yvxuabxcpvc2hy2.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A sintaxe básica para realizar um JOIN envolve especificar as tabelas envolvidas e as condições de junção, geralmente definidas pela cláusula ON, onde são indicados os campos relacionados nas tabelas.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6a1eudj5xd29cgqdm797.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6a1eudj5xd29cgqdm797.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;LEFT JOIN&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Retorna todos os registros da tabela à esquerda (primeira tabela listada), juntamente com os registros correspondentes da tabela à direita (segunda tabela listada). Se não houver correspondência na tabela à direita, os campos associados a essa tabela conterão valores nulos.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9tsv62yjyuje9mu35502.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9tsv62yjyuje9mu35502.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Para fazer esse join utilizamos o seguinte comando:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fet64m50xj84gb0ph0n94.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fet64m50xj84gb0ph0n94.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Podemos fazer o LEFT JOIN excluindo os valores do INNER JOIN, isso chamamos de LEFT JOIN EXCLUDING INNER JOIN&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpup4yjxpm3nbxq68ul7o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpup4yjxpm3nbxq68ul7o.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Para fazer esse join utilizamos o seguinte comando:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4h6j0eyhrc6gcjmnr745.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4h6j0eyhrc6gcjmnr745.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;RIGHT JOIN&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Similar ao LEFT JOIN, porém retorna todos os registros da tabela à direita, com seus correspondentes da tabela à esquerda. Registros sem correspondência na tabela à esquerda resultarão em valores nulos nos campos associados a essa tabela.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl04e2xk5grvnyz8c7nsf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl04e2xk5grvnyz8c7nsf.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Para fazer esse join utilizamos o seguinte comando:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fflv2a4prpniwxhtasavg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fflv2a4prpniwxhtasavg.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Assim como no LEFT JOIN, podemos também no RIGHT JOIN excluir os resultados do INNER JOIN, chamamos de RIGHT JOIN EXCLUDING INNER JOIN.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcvniz7yp48zwy4t0clvw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcvniz7yp48zwy4t0clvw.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Para fazer esse join utilizamos o seguinte comando:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feetyx6u02sa5e9x99tls.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feetyx6u02sa5e9x99tls.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;FULL OUTER JOIN&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Ou apenas FULL JOIN, retorna todos os registros de ambas as tabelas, incluindo os registros que não têm correspondência na tabela oposta. Campos sem correspondência conterão valores nulos.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2sfssvaejwxqnsefa1or.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2sfssvaejwxqnsefa1or.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Para fazer esse join utilizamos o seguinte comando:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feqwz50qd9oe3n8fcldv5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feqwz50qd9oe3n8fcldv5.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Temos também o FULL JOIN EXCLUDING INNER JOIN, que é o FULL JOIN excluindo o INNER JOIN. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6p5ya8mh66w5yaoepnwm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6p5ya8mh66w5yaoepnwm.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Para fazer esse join utilizamos o seguinte comando:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F43g0podpp8qj5vwqg6f2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F43g0podpp8qj5vwqg6f2.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CROSS JOIN&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;É um tipo de junção que combina todas as linhas de duas ou mais tabelas envolvidas, produzindo um conjunto de resultados que é o produto cartesiano dessas tabelas. Isso significa que cada linha da primeira tabela será combinada com todas as linhas da segunda tabela e assim por diante, gerando todas as possíveis combinações.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sintaxe&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fez6f8oo4lkvnnm0vefxg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fez6f8oo4lkvnnm0vefxg.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Repare que não temos o "ON A.CHAVE = B.CHAVE" nesse caso, isso por que não estamos relacionando as colunas.&lt;/p&gt;

&lt;p&gt;Nesse exemplo, a consulta retorna todas as combinações possíveis entre a tabela A e a tabela B. Se houver 10 registros na tabela A e 5 registros na tabela B, o resultado conterá 50 linhas, combinando cada registro da tabela A com todos os registros da tabela B.&lt;/p&gt;

&lt;p&gt;Geralmente, o CROSS JOIN não é tão utilizado quanto outros tipos de JOINs, pois na maioria dos casos estamos interessados em combinar registros com base em critérios de relacionamento específicos. Entretanto, em alguns cenários, pode ser útil, como para gerar combinações cartesianas ou para produzir resultados específicos em relatórios complexos.&lt;/p&gt;

&lt;p&gt;Abaixo temos uma imagem com um resumo dos JOINs mais comuns.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2mkwd5gexxoseom2jia1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2mkwd5gexxoseom2jia1.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Em conclusão, as cláusulas JOIN no SQL são uma parte essencial da manipulação e análise de dados em bancos de dados relacionais. Elas permitem que você una dados de várias tabelas com base em relações-chave, expandindo assim a capacidade de extrair informações valiosas a partir de conjuntos de dados interconectados.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Conexão de Dados&lt;/strong&gt;: As cláusulas JOIN permitem que você combine informações de diferentes tabelas, o que é fundamental para a construção de consultas complexas que recuperam dados relacionados de várias fontes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Diversos Tipos de JOIN&lt;/strong&gt;: SQL oferece diferentes tipos de joins, como INNER JOIN, LEFT JOIN, RIGHT JOIN e FULL JOIN, cada um adequado a um cenário específico. Isso proporciona flexibilidade na recuperação de dados.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Relações Complexas&lt;/strong&gt;: As joins são cruciais quando você lida com bases de dados complexas que têm muitas tabelas com relacionamentos entre elas. Elas ajudam a trazer clareza e organização aos seus dados.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Tomada de Decisões Baseada em Dados&lt;/strong&gt;: O domínio das cláusulas JOIN é essencial para profissionais que buscam obter informações precisas a partir de bancos de dados, o que, por sua vez, sustenta a tomada de decisões informadas.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Em resumo, a compreensão das cláusulas JOIN no SQL é uma habilidade crucial para qualquer pessoa que trabalha com dados em um ambiente de banco de dados relacional. Dominar a arte de unir e relacionar tabelas permite que você extraia insights valiosos, construa relatórios complexos e, em última análise, tome decisões embasadas em dados sólidos. Portanto, aprofundar o conhecimento sobre joins é um passo importante na jornada para se tornar um profissional eficiente em gerenciamento e análise de dados.&lt;/p&gt;

</description>
      <category>database</category>
      <category>sql</category>
      <category>learning</category>
      <category>programming</category>
    </item>
    <item>
      <title>Understanding WHERE and ORDER BY</title>
      <dc:creator>Nathalia Friederichs</dc:creator>
      <pubDate>Mon, 30 Oct 2023 22:03:54 +0000</pubDate>
      <link>https://dev.to/nathalia_friederichs/understanding-where-and-order-by-4j7i</link>
      <guid>https://dev.to/nathalia_friederichs/understanding-where-and-order-by-4j7i</guid>
      <description>&lt;p&gt;Let's delve a bit deeper into the SQL commands WHERE and ORDER BY.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conditional Operators&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First of all, we need to understand conditional operators. They are used in conjunction with the WHERE clause in SQL queries to filter data and retrieve specific records.&lt;/p&gt;

&lt;p&gt;The following table explains the most common conditional operators:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--WhOQIf4J--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t8y12fdkpa2un8988r6h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--WhOQIf4J--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t8y12fdkpa2un8988r6h.png" alt="Image description" width="399" height="283"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The WHERE Command&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The WHERE command is used to filter records in a table based on certain conditions. You can use WHERE to filter records based on a single column or multiple columns simultaneously.&lt;/p&gt;

&lt;p&gt;In the example below, we are using WHERE on just one column, selecting only an ID that has been specified.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Syntax&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--YdG87eWW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t8r556elkx9jfj2a38qe.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--YdG87eWW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t8r556elkx9jfj2a38qe.png" alt="Image description" width="746" height="79"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the next example, we're selecting all records with an age equal to 20 and 21.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Syntax&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--DMHFke0C--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ifbftztgy54o4txm74z3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--DMHFke0C--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ifbftztgy54o4txm74z3.png" alt="Image description" width="748" height="84"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you want to filter based on multiple columns, you can use the WHERE clause with the logical operators AND or OR.&lt;/p&gt;

&lt;p&gt;Using the AND operator, the result will include all records that meet all the specified criteria. In the example below, all records with an age of 20 and 21 and residing in New York will be returned.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Syntax&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--vpNAOJ83--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z72ox4cgztdiuqvlvxhn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--vpNAOJ83--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z72ox4cgztdiuqvlvxhn.png" alt="Image description" width="741" height="101"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Similarly, if you want to retrieve customers who are over 20 years old or are from the city of New York, you can use the OR operator.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Syntax&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--pvI3SPWg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pga59b1jneel8giju8ej.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--pvI3SPWg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pga59b1jneel8giju8ej.png" alt="Image description" width="749" height="101"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you want to filter all records where the name starts with the letter L, for example, you can use the LIKE command.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Syntax&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--rDhqmnBx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x0mpn7r4ai85agp8if3p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--rDhqmnBx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x0mpn7r4ai85agp8if3p.png" alt="Image description" width="750" height="84"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Notice that we only use the % after the letter L. This indicates that I want the first letter to be L, and the subsequent letters don't matter.&lt;/p&gt;

&lt;p&gt;If I want all records that end with L, I would place the % before the L.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Syntax&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--EB67a7mH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lzvjzwup3pd46sfpzauo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--EB67a7mH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lzvjzwup3pd46sfpzauo.png" alt="Image description" width="748" height="83"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The ORDER BY Command&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We use the ORDER BY command when we want the result of our SELECT statement to be in a specific order. There are various ways to use this command.&lt;/p&gt;

&lt;p&gt;In this first example, let's sort by age in ascending order.&lt;br&gt;
Syntax&lt;/p&gt;

&lt;p&gt;To sort by age in descending order:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Syntax&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--EiNIYtx_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ivyspdsefcglpscd27z.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--EiNIYtx_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ivyspdsefcglpscd27z.png" alt="Image description" width="746" height="81"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can also sort by more than one column. For example, we can sort by age and then by date of birth.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Syntax&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--_xKKX-A---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wk505he9d7j5v9t39ntm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--_xKKX-A---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wk505he9d7j5v9t39ntm.png" alt="Image description" width="745" height="80"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>sql</category>
      <category>database</category>
      <category>learning</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Entendendo o WHERE e o ORDER BY</title>
      <dc:creator>Nathalia Friederichs</dc:creator>
      <pubDate>Sat, 21 Oct 2023 00:26:41 +0000</pubDate>
      <link>https://dev.to/nathalia_friederichs/entendendo-o-where-e-o-order-by-2c87</link>
      <guid>https://dev.to/nathalia_friederichs/entendendo-o-where-e-o-order-by-2c87</guid>
      <description>&lt;p&gt;Vamos entender um pouco melhor os comandos WHERE e ORDER BY do SQL.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Operadores condicionais&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Antes de tudo, precisamos entender um pouco sobre os operadores condicionais. São eles que vamos utilizar junto com o WHERE para trazer exatamente os registros que queremos. Para facilitar o entendimento, trouxe a tabela abaixo que explica de forma sucinta esses operadores.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--1lnBO3m8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uka5bo6lz9iyf662cy53.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1lnBO3m8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uka5bo6lz9iyf662cy53.png" alt="Image description" width="401" height="281"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;O comando WHERE&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;O comando WHERE é utilizado quando queremos localizar na tabela algum registro com base em algumas condições. É possível empregar o WHERE para filtrar registros com base em uma única coluna ou em várias colunas simultaneamente.&lt;/p&gt;

&lt;p&gt;No exemplo abaixo, estamos fazendo um WHERE em apenas uma coluna, pegando apenas um CPF que foi especificado.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sintaxe&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--2ErUkN99--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2thgqt8zi9bpa6u9hj2p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--2ErUkN99--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2thgqt8zi9bpa6u9hj2p.png" alt="Image description" width="800" height="92"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Já nesse próximo exemplo, estamos pegando todos os registros que têm idade igual a 20 e 21.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sintaxe&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Y5OzJKFn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hb4gv3zlgssgfhid822k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Y5OzJKFn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hb4gv3zlgssgfhid822k.png" alt="Image description" width="800" height="93"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Caso você queira filtrar mais de uma coluna, pode usar a cláusula WHERE com o operador lógico AND ou OR.&lt;/p&gt;

&lt;p&gt;Usando o operador AND o retorno será todos os registros que atendam a todos critérios estabelecidos. No exemplo abaixo, serão retornados todos com idade igual a 20 e 21 e que a cidade seja São Paulo.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sintaxe&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--2Oi36SMd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mjbsj2nbg0rjubm3e0e0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--2Oi36SMd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mjbsj2nbg0rjubm3e0e0.png" alt="Image description" width="800" height="119"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Da mesma forma, se você quiser recuperar os clientes que têm mais de 20 anos ou são da cidade de São Paulo, você pode usar o operador OR.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sintaxe&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--GK8ZVsDx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/axk8vo6jo4odg29s1y5f.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--GK8ZVsDx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/axk8vo6jo4odg29s1y5f.png" alt="Image description" width="800" height="116"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Caso você queira filtrar todos os registros em que o nome começa com a letra L, por exemplo, pode usar o comando LIKE.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sintaxe&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--zUY_UdmC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0yq1601tld1oqycyj22y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--zUY_UdmC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0yq1601tld1oqycyj22y.png" alt="Image description" width="754" height="83"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Repare que só utilizamos o % depois da letra L, com isso eu estou dizendo que quero que a primeira letra seja o L, e que depois não importa quais sejam as letras. &lt;/p&gt;

&lt;p&gt;Se eu quiser todos os registros que terminam com L, eu colocaria o % antes do L.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sintaxe&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--0eobSEJo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zjbeh3t5dyknhsgk8f7l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--0eobSEJo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zjbeh3t5dyknhsgk8f7l.png" alt="Image description" width="748" height="83"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;O comando ORDER BY&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Utilizamos o comando ORDER BY quando queremos que o retorno do nosso select esteja em uma ordem específica. Há vários jeitos de fazer esse comando.&lt;/p&gt;

&lt;p&gt;Nesse primeiro exemplo, vamos ordenar por idade de forma crescente.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sintaxe&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--vcyvMDGf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f3qnj3fr0bwsntlxu0am.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--vcyvMDGf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f3qnj3fr0bwsntlxu0am.png" alt="Image description" width="747" height="81"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Para ordenar por idade de forma decrescente:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sintaxe&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--o2RAkvgN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9mbhqsu8008s31khudxm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--o2RAkvgN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9mbhqsu8008s31khudxm.png" alt="Image description" width="749" height="82"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Também podemos ordenar por mais de uma coluna, por exemplo, por idade e data de nascimento.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sintaxe&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--7AJ5fC76--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gak89cqpric0wg4n78xx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--7AJ5fC76--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gak89cqpric0wg4n78xx.png" alt="Image description" width="751" height="81"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>database</category>
      <category>sql</category>
      <category>programming</category>
      <category>learning</category>
    </item>
  </channel>
</rss>
