1661561640
A engenharia de dados e a ciência de dados são campos competitivos e em rápida evolução. As tecnologias vêm e vão, portanto, manter seu conjunto de habilidades atualizado é algo com o qual todos os profissionais de dados ambiciosos podem concordar. Onde engenheiros de dados e cientistas discordam é exatamente quais habilidades serão mais valiosas no futuro.
Independentemente da desconcertante variedade de ferramentas e serviços disponíveis para cientistas de dados, ainda é o SQL humilde que forma a base da pilha de um cientista de dados. Embora o SQL seja geralmente visto como uma habilidade básica, na verdade é muito mais do que isso. Apesar de ter quase 50 anos, o SQL está se tornando mais, não menos relevante.
Aprendizado de máquina, análise de big data ou IA podem roubar as manchetes, mas se você deseja aprimorar uma habilidade inteligente e estratégica que pode elevar sua carreira, não procure mais do que o SQL. Aqui está o porquê.
Primeiramente, “SQL é realmente a linguagem dos dados” nas palavras de Benjamn Rogojan (também conhecido como Seattle Data Guy). Isso se deve ao fato de que a maioria dos bancos de dados é construída em uma ou outra das tecnologias baseadas em SQL. Todos, exceto dois, dos dez principais bancos de dados mais populares hoje são baseados em SQL, as exceções (MongoDB e Redis) são classificadas em quinto e sexto, respectivamente, e até mesmo podem ser usadas com SQL. É fácil ver por que qualquer pessoa que precise consultar, atualizar, alterar ou de qualquer forma se envolver com dados em bancos de dados relacionais será bem atendida com um sólido conhecimento prático de SQL, independentemente da especialização que eles acabem buscando.
Apesar de sua idade, o SQL está longe de ser uma habilidade herdada. À medida que a engenharia de dados avançou para a nuvem, o SQL seguiu e, de acordo com a Dataquest, o SQL foi a habilidade mais demandada entre todos os trabalhos em dados em 2021, especialmente na extremidade mais júnior do espectro. No entanto, anúncios de emprego de cientistas de dados ainda mais experientes ainda listam SQL em quase 60% das vagas. Além disso, sem dúvida devido à crescente demanda por conhecimento relacionado a dados, a demanda por habilidades em SQL parece estar crescendo, apesar de uma breve queda em 2020. Pandemia à parte, o mercado de transformação de servidores SQL – que ajuda as empresas a atender à necessidade de transformação de dados – é previsto para crescer de forma constante em mais de 10 por cento CAGR até o final da década.
O futuro do SQL parece seguro, mas isso não significa necessariamente que os cientistas de dados iniciantes que já têm um conhecimento prático dele priorizem o aprofundamento de suas habilidades de SQL para promover seu progresso na carreira.
Eles deviam.
Com tantas ferramentas e tecnologias nascentes para ajudá-los no estágio de ELT/ETL, para BI e para análises preditivas e históricas, os cientistas de dados precisam saber onde investir sua energia. A meia-vida cada vez menor das habilidades de alta tecnologia significa que as ferramentas e habilidades dos cientistas de dados
aprender pode ser definidor de carreira – ou limitador de carreira.
Ninguém quer passar seis meses descobrindo uma ferramenta que oferece apenas metade do que se esperava dela, muito menos recomendá-la para a equipe mais ampla apenas para descobrir que ela deixa a desejar. Portanto, quando os cientistas de dados analisam os serviços e técnicas disponíveis que os ajudarão a consultar seus dados com mais eficiência,
eles provavelmente examinarão as melhores ferramentas de BI e extensões de ML que permitirão preparar os dados, criar o modelo e treiná-lo. Mas todas essas diferentes etapas levam tempo e exigem altos níveis de especialização. Fomos condicionados a aceitar que a modelagem de ML exige que os dados sejam extraídos do banco de dados, geralmente usando uma ferramenta de BI, transformados e carregados no sistema de BI, antes de serem exportados (novamente) para a ferramenta de ML, onde a mágica acontece, e transportando-o de volta para a ferramenta de BI para visualização.
E se eu lhe disser que existe uma maneira de levar modelos de ML aos dados, permitindo que você consulte previsões de dentro do banco de dados usando – você adivinhou – SQL? Há. Faz parte de um pequeno, mas em rápido crescimento
movimento que traz inteligência para a camada de dados, em vez de levar os dados meticulosamente para a ferramenta de ML.
O ML no banco de dados é uma maneira muito mais simples de usar dados existentes para prever eventos futuros... e usa comandos SQL padrão. ML no banco de dados é um pouco como dar um cérebro ao seu banco de dados. Isso significa que cientistas de dados – e engenheiros de dados e, de fato, qualquer pessoa com habilidades em SQL – podem trabalhar no banco de dados, executando modelos de ML para responder a praticamente qualquer pergunta de negócios. Prever a perda de clientes, pontuação de crédito, otimização do ciclo de vida do cliente, detecção de fraudes, gerenciamento de estoque, modelagem de preços e previsão de resultados de saúde do paciente são apenas alguns dos muitos casos de uso que a modelagem no banco de dados permitiu. Com essa abordagem, todos os modelos de ML podem ser criados, consultados e mantidos como se fossem tabelas de banco de dados, usando a linguagem SQL e trazendo recursos preditivos poderosos para uma gama muito maior de profissionais de dados.
O ML no banco de dados é um campo relativamente novo, mas faz parte de um movimento mais amplo e de rápido crescimento para simplificar e democratizar a engenharia de dados e a ciência de dados, derrubando as barreiras técnicas que existem atualmente para quem trabalha com dados. Veja, por exemplo, a dbt Labs, uma empresa que conquistou o mundo dos dados, tendo recentemente garantido US$ 222 milhões em financiamento e avaliado em US$ 4,2 bilhões. Seu produto de transformação de dados permite que engenheiros de dados criem pipelines de dados de nível de produção a partir do data warehouse usando comandos SQL, simplificando radicalmente e acelerando o processo de preparação de dados.
Temos a sorte de estar vivendo em uma era de ouro da inovação digital. No entanto, em um cenário de negócios que valoriza os insights que os dados podem oferecer, os cientistas de dados estão sob pressão como nunca antes para produzir milagres a partir dos dados. Uma gama estonteante de ferramentas e serviços surgiu da necessidade de acelerar e dimensionar a análise de dados. Essas ferramentas geralmente exigem um investimento em tempo e desenvolvimento de habilidades para obter plenamente seus benefícios. No entanto, uma habilidade que muitas vezes tem sido negligenciada é o SQL humilde, o melhor amigo do cientista de dados. O SQL não só não vai a lugar nenhum, como mostra o crescente movimento para inovar mais perto dos dados, o SQL está se tornando a arma secreta estratégica do cientista de dados.
Fonte: https://www.kdnuggets.com
1594369800
SQL stands for Structured Query Language. SQL is a scripting language expected to store, control, and inquiry information put away in social databases. The main manifestation of SQL showed up in 1974, when a gathering in IBM built up the principal model of a social database. The primary business social database was discharged by Relational Software later turning out to be Oracle.
Models for SQL exist. In any case, the SQL that can be utilized on every last one of the major RDBMS today is in various flavors. This is because of two reasons:
1. The SQL order standard is genuinely intricate, and it isn’t handy to actualize the whole standard.
2. Every database seller needs an approach to separate its item from others.
Right now, contrasts are noted where fitting.
#programming books #beginning sql pdf #commands sql #download free sql full book pdf #introduction to sql pdf #introduction to sql ppt #introduction to sql #practical sql pdf #sql commands pdf with examples free download #sql commands #sql free bool download #sql guide #sql language #sql pdf #sql ppt #sql programming language #sql tutorial for beginners #sql tutorial pdf #sql #structured query language pdf #structured query language ppt #structured query language
1596441660
When you develop large chunks of T-SQL code with the help of the SQL Server Management Studio tool, it is essential to test the “Live” behavior of your code by making sure that each small piece of code works fine and being able to allocate any error message that may cause a failure within that code.
The easiest way to perform that would be to use the T-SQL debugger feature, which used to be built-in over the SQL Server Management Studio tool. But since the T-SQL debugger feature was removed completely from SQL Server Management Studio 18 and later editions, we need a replacement for that feature. This is because we cannot keep using the old versions of SSMS just to support the T-SQL Debugger feature without “enjoying” the new features and bug fixes that are released in the new SSMS versions.
If you plan to wait for SSMS to bring back the T-SQL Debugger feature, vote in the Put Debugger back into SSMS 18 to ask Microsoft to reintroduce it.
As for me, I searched for an alternative tool for a T-SQL Debugger SSMS built-in feature and found that Devart company rolled out a new T-SQL Debugger feature to version 6.4 of SQL – Complete tool. SQL Complete is an add-in for Visual Studio and SSMS that offers scripts autocompletion capabilities, which help develop and debug your SQL database project.
The SQL Debugger feature of SQL Complete allows you to check the execution of your scripts, procedures, functions, and triggers step by step by adding breakpoints to the lines where you plan to start, suspend, evaluate, step through, and then to continue the execution of your script.
You can download SQL Complete from the dbForge Download page and install it on your machine using a straight-forward installation wizard. The wizard will ask you to specify the installation path for the SQL Complete tool and the versions of SSMS and Visual Studio that you plan to install the SQL Complete on, as an add-in, from the versions that are installed on your machine, as shown below:
Once SQL Complete is fully installed on your machine, the dbForge SQL Complete installation wizard will notify you of whether the installation was completed successfully or the wizard faced any specific issue that you can troubleshoot and fix easily. If there are no issues, the wizard will provide you with an option to open the SSMS tool and start using the SQL Complete tool, as displayed below:
When you open SSMS, you will see a new “Debug” tools menu, under which you can navigate the SQL Debugger feature options. Besides, you will see a list of icons that will be used to control the debug mode of the T-SQL query at the leftmost side of the SSMS tool. If you cannot see the list, you can go to View -> Toolbars -> Debugger to make these icons visible.
During the debugging session, the SQL Debugger icons will be as follows:
The functionality of these icons within the SQL Debugger can be summarized as:
#sql server #sql #sql debugger #sql server #sql server stored procedure #ssms #t-sql queries
1596448980
Let’s say the chief credit and collections officer asks you to list down the names of people, their unpaid balances per month, and the current running balance and wants you to import this data array into Excel. The purpose is to analyze the data and come up with an offer making payments lighter to mitigate the effects of the COVID19 pandemic.
Do you opt to use a query and a nested subquery or a join? What decision will you make?
Before we do a deep dive into syntax, performance impact, and caveats, why not define a subquery first?
In the simplest terms, a subquery is a query within a query. While a query that embodies a subquery is the outer query, we refer to a subquery as the inner query or inner select. And parentheses enclose a subquery similar to the structure below:
SELECT
col1
,col2
,(subquery) as col3
FROM table1
[JOIN table2 ON table1.col1 = table2.col2]
WHERE col1 <operator> (subquery)
We are going to look upon the following points in this post:
As is customary, we provide examples and illustrations to enhance understanding. But bear in mind that the main focus of this post is on subqueries in SQL Server.
Now, let’s get started.
For one thing, subqueries are categorized based on their dependency on the outer query.
Let me describe what a self-contained subquery is.
Self-contained subqueries (or sometimes referred to as non-correlated or simple subqueries) are independent of the tables in the outer query. Let me illustrate this:
-- Get sales orders of customers from Southwest United States
-- (TerritoryID = 4)
USE [AdventureWorks]
GO
SELECT CustomerID, SalesOrderID
FROM Sales.SalesOrderHeader
WHERE CustomerID IN (SELECT [CustomerID]
FROM [AdventureWorks].[Sales].[Customer]
WHERE TerritoryID = 4)
As demonstrated in the above code, the subquery (enclosed in parentheses below) has no references to any column in the outer query. Additionally, you can highlight the subquery in SQL Server Management Studio and execute it without getting any runtime errors.
Which, in turn, leads to easier debugging of self-contained subqueries.
The next thing to consider is correlated subqueries. Compared to its self-contained counterpart, this one has at least one column being referenced from the outer query. To clarify, I will provide an example:
USE [AdventureWorks]
GO
SELECT DISTINCT a.LastName, a.FirstName, b.BusinessEntityID
FROM Person.Person AS p
JOIN HumanResources.Employee AS e ON p.BusinessEntityID = e.BusinessEntityID
WHERE 1262000.00 IN
(SELECT [SalesQuota]
FROM Sales.SalesPersonQuotaHistory spq
WHERE p.BusinessEntityID = spq.BusinessEntityID)
Were you attentive enough to notice the reference to BusinessEntityID from the Person table? Well done!
Once a column from the outer query is referenced in the subquery, it becomes a correlated subquery. One more point to consider: if you highlight a subquery and execute it, an error will occur.
And yes, you are absolutely right: this makes correlated subqueries pretty harder to debug.
To make debugging possible, follow these steps:
Isolating the subquery for debugging will make it look like this:
SELECT [SalesQuota]
FROM Sales.SalesPersonQuotaHistory spq
WHERE spq.BusinessEntityID = <constant value>
Now, let’s dig a little deeper into the output of subqueries.
Well, first, let’s think of what returned values can we expect from SQL subqueries.
In fact, there are 3 possible outcomes:
Let’s start with single-valued output. This type of subquery can appear anywhere in the outer query where an expression is expected, like the WHERE clause.
-- Output a single value which is the maximum or last TransactionID
USE [AdventureWorks]
GO
SELECT TransactionID, ProductID, TransactionDate, Quantity
FROM Production.TransactionHistory
WHERE TransactionID = (SELECT MAX(t.TransactionID)
FROM Production.TransactionHistory t)
When you use a MAX() function, you retrieve a single value. That’s exactly what happened to our subquery above. Using the equal (=) operator tells SQL Server that you expect a single value. Another thing: if the subquery returns multiple values using the equals (=) operator, you get an error, similar to the one below:
Msg 512, Level 16, State 1, Line 20
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Next, we examine the multi-valued output. This kind of subquery returns a list of values with a single column. Additionally, operators like IN and NOT IN will expect one or more values.
-- Output multiple values which is a list of customers with lastnames that --- start with 'I'
USE [AdventureWorks]
GO
SELECT [SalesOrderID], [OrderDate], [ShipDate], [CustomerID]
FROM Sales.SalesOrderHeader
WHERE [CustomerID] IN (SELECT c.[CustomerID] FROM Sales.Customer c
INNER JOIN Person.Person p ON c.PersonID = p.BusinessEntityID
WHERE p.lastname LIKE N'I%' AND p.PersonType='SC')
And last but not least, why not delve into whole table outputs.
-- Output a table of values based on sales orders
USE [AdventureWorks]
GO
SELECT [ShipYear],
COUNT(DISTINCT [CustomerID]) AS CustomerCount
FROM (SELECT YEAR([ShipDate]) AS [ShipYear], [CustomerID]
FROM Sales.SalesOrderHeader) AS Shipments
GROUP BY [ShipYear]
ORDER BY [ShipYear]
Have you noticed the FROM clause?
Instead of using a table, it used a subquery. This is called a derived table or a table subquery.
And now, let me present you some ground rules when using this sort of query:
In this case, a derived table has the benefits of a physical table. That’s why in our example, we can use COUNT() in one of the columns of the derived table.
That’s about all regarding subquery outputs. But before we get any further, you may have noticed that the logic behind the example for multiple values and others as well can also be done using a JOIN.
-- Output multiple values which is a list of customers with lastnames that start with 'I'
USE [AdventureWorks]
GO
SELECT o.[SalesOrderID], o.[OrderDate], o.[ShipDate], o.[CustomerID]
FROM Sales.SalesOrderHeader o
INNER JOIN Sales.Customer c on o.CustomerID = c.CustomerID
INNER JOIN Person.Person p ON c.PersonID = p.BusinessEntityID
WHERE p.LastName LIKE N'I%' AND p.PersonType = 'SC'
In fact, the output will be the same. But which one performs better?
Before we get into that, let me tell you that I have dedicated a section to this hot topic. We’ll examine it with complete execution plans and have a look at illustrations.
So, bear with me for a moment. Let’s discuss another way to place your subqueries.
#sql server #sql query #sql server #sql subqueries #t-sql statements #sql
1621850444
When working in the SQL Server, we may have to check some other databases other than the current one which we are working. In that scenario we may not be sure that does we have access to those Databases?. In this article we discuss the list of databases that are available for the current logged user in SQL Server
#sql server #available databases for current user #check database has access #list of available database #sql #sql query #sql server database #sql tips #sql tips and tricks #tips
1603760400
This article will introduce the concept of SQL recursive. Recursive CTE is a really cool. We will see that it can often simplify our code, and avoid a cascade of SQL queries!
The recursive queries are used to query hierarchical data. It avoids a cascade of SQL queries, you can only do one query to retrieve the hierarchical data.
First, what is a CTE? A CTE (Common Table Expression) is a temporary named result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. For example, you can use CTE when, in a query, you will use the same subquery more than once.
A recursive CTE is one having a subquery that refers to its own name!
Recursive CTE is defined in the SQL standard.
A recursive CTE has this structure:
In this example, we use hierarchical data. Each row can have zero or one parent. And it parent can also have a parent etc.
Create table test (id integer, parent_id integer);
insert into test (id, parent_id) values (1, null);
insert into test (id, parent_id) values (11, 1);
insert into test (id, parent_id) values (111, 11);
insert into test (id, parent_id) values (112, 11);
insert into test (id, parent_id) values (12, 1);
insert into test (id, parent_id) values (121, 12);
For example, the row with id 111 has as ancestors: 11 and 1.
Before knowing the recursive CTE, I was doing several queries to get all the ancestors of a row.
For example, to retrieve all the ancestors of the row with id 111.
While (has parent)
Select id, parent_id from test where id = X
With recursive CTE, we can retrieve all ancestors of a row with only one SQL query :)
WITH RECURSIVE cte_test AS (
SELECT id, parent_id FROM test WHERE id = 111
UNION
SELECT test.id, test.parent_id FROM test JOIN cte_test ON cte_test.id = test.parent_id
) SELECT * FROM cte_test
Explanations:
It indicates we will make recursive
It is the initial query.
It is the recursive expression! We make a jointure with the current CTE!
Replay this example here
#sql #database #sql-server #sql-injection #writing-sql-queries #sql-beginner-tips #better-sql-querying-tips #sql-top-story