Cómo Protegerse Contra La Inyección Ciega De SQL

Uno de los principales problemas en el mundo de las bases de datos es la inyección de SQL: prevalece hasta tal punto que incluso OWASP la enumera continuamente como la amenaza número 1 dirigida a las aplicaciones web . La inyección de SQL puede tener muchos tipos y uno de estos tipos es la inyección de SQL ciega: en esta publicación de blog, veremos cuán dañino puede ser un ataque de este tipo.

¿Qué es la inyección SQL? ¿Cuáles son sus Categorías?

Como ya le dijimos en algunas de nuestras publicaciones de blog anteriores , la inyección de SQL es el principal ataque dirigido a las bases de datos: una aplicación es vulnerable a la inyección de SQL cuando una entrada proporcionada por un usuario se envía directamente a una base de datos sin ser desinfectada y correctamente tratado.

Es muy importante entender las categorías de inyección SQL por un par de razones clave:

  • Los diferentes tipos de inyección SQL impactan en las aplicaciones web de diferentes maneras.
  • Algunos tipos de inyección SQL se pueden prevenir más fácilmente que otros.
  • Algunos tipos de inyección SQL dependen directamente de las características de nuestras aplicaciones web (por ejemplo, los resultados de un ataque de inyección SQL ciego exitoso dependen directamente de si nuestra aplicación web muestra errores o no).
  • Algunos tipos de ataques de inyección SQL tienen subtipos (piense en la inyección SQL ciega basada en el tiempo): estos subtipos también pueden hacer o deshacer un trato para una parte nefasta porque dependen directamente de un factor específico que, en este caso, no se puede controlar, por lo que son directamente - tiempo.

La inyección SQL tiene un par de categorías:

Como puede ver, no hay muchas categorías en las que caiga la inyección de SQL; sin embargo, mientras que la inyección de SQL clásica se usa con más frecuencia, cuando los ataques de inyección de SQL clásicos no funcionan, los atacantes generalmente recurren al lado ciego de SQL: intentan atacando aplicaciones con inyección ciega de SQL.

El Reino de la Inyección SQL Ciega

Think of your application as a castle. We know, this might seem at least a little bit odd, but bear with us. Now, imagine your web application as a castle. Done? Okay, imagine that a bunch of blind soldiers with spears are attacking it and their spears frequently miss the fortified defenses of the castle. What do you think — how much time the blind soldiers with spears have to spare to be done with your castle’s defenses? It will take a while, but the soldiers will eventually get through. That’s true — and once the soldiers get through, the treasures you store in your castle (the data inside of your web applications) are cactus — they will steal everything.

Soldiers are well-equipped, and even though they are blind, they will eventually perpetrate your defenses — oh, noes! That’s pretty much how blind SQL injection works in the real world, so let us give you another example:

  1. An attacker finds your web application to be vulnerable to a blind form of SQL injection by adding a single quote after a certain parameter — then your web application returns an error.
  2. An attacker keeps crafting SQL queries — none of them return any error. However, he quickly finds that if he executes one type of a query, the data inside of your web application shows on the screen, after he executes another — the data disappears. “Aha!”, — thinks the attacker. “Gotcha. Got a blind SQL injection flaw.”

As you might already notice, a blind SQL injection is such an attack that asks the database “questions” in a form of queries and tries to determine whether they are true or false based on the response on the web application. Blind SQL injection is most frequently detected by running queries like so:

If a web application returns a “positive” response (meaning that it returns a visible difference on a web page), the web application is susceptible to such an attack, while if an application is indifferent, it is probably not. In the first scenario, the attacker will know something’s up with your database and try to penetrate your defenses even further. And so the game begins — the attacker is trying to notice what kind of responses your web application is willing to return. A query returns a page with results — OK, he probes further, a query returns a blank page — hmmm… he changes the query and tries again. And so the game continues until all data that interests a nefarious party is extracted from your database. Yes, such kind of querying willtomar mucho tiempo (y esa es una de las cosas por las que la inyección ciega de SQL es más conocida), pero tenga en cuenta que el tiempo, por triste que sea, probablemente no detendrá a un atacante que tiene como objetivo dañar sus sistemas como tanto como sea posible o robar todos sus datos.

Some web applications might even filter the parts in GET or POST parameters meaning that they might “catch” single or double quotes being used, but that’s only one piece of the puzzle. Such a function is frequently a part of a web application firewall type of functionality — we have already discussed WAFs (short for Web Application Firewalls) in another article of ours, so we won’t go too much into detail, but keep in mind that web application firewalls deflect all kinds of attacks ranging from Denial of Service to, you guessed it, SQL injection. You can find a live example of a web application firewall by visiting the website of one of the biggest & fastest data breach search engines in the world — BreachDirectory — but for now, let’s get back to the topic.

Types of Blind SQL Injection

Hay dos tipos de inyección SQL ciega: basada en booleanos y basada en el tiempo. La inyección SQL ciega basada en booleanos depende del envío de una determinada consulta SQL a la base de datos para determinar si la consulta devuelve un resultado TRUEo FALSEal observar la respuesta de la aplicación, mientras que la inyección SQL basada en el tiempo depende del tiempo: una consulta que prueba un aplicación web para la inyección de SQL basada en tiempo ciego obligará a la base de datos a esperar un par de segundos antes de devolver una respuesta, y si la respuesta se devuelve después de que hayan pasado la cantidad exacta de segundos especificados, el atacante podrá determinar que la aplicación es susceptible a la inyección SQL ciega basada en el tiempo. Aquí hay un par de diferencias y similitudes clave entre los dos tipos:

Protección contra la inyección ciega de SQL

Protecting from a blind type of SQL injection, contrary to popular belief, does not take much skill or effort — it can be prevented using basic security measures. Yes, it’s as simple as that! We can accomplish that by using Prepared Data Objects (PDO) in PHP (they split the input provided by the user and the rest of the query, thus any kind of SQL injection is not possible), by using automated testing solutions that inform us whether or not our application is susceptible to SQLi, or, of course, using whitelist security controls — we, as developers, should have a habit of filtering and sanitizing every kind of parameter that somehow interacts with our data. By doing that we can put our web applications at the next security level both by protecting against all kinds of SQL injection attacks and other types of security issues.

Once we put our web applications at the next level of security, we must take care of the security of our own accounts too — we can run a search through BreachDirectory to see if any of our accounts are at risk and act according to the advice given to us. Once we do that, our accounts should be secure as well. Win — win!

Summary

Blind SQL injection is a type of SQL injection where an attacker cannot figure out how our web applications “think”, so instead they have to rely on the output a web application gives us or rely on time, depending on which method (boolean-based or time-based) is in use. When relying on boolean-based SQL injection, an attacker counts on the fact that the web application might look different than usual, while when using time-based SQL injection, the attacker heavily relies on time.

No matter what type of SQL injection is elected to use by the attacker, no type provides the attacker with a quick way to gain data — an attacker may literally spend hours, days, or even months gaining data of interest to him, but once the attack is successfully accomplished, it will usually be sold on the dark web for thousands of dollars to other nefarious parties, and the cycle will continue.

To protect against blind SQL injection, make sure to employ secure coding practices, do not forward user input straight into a database, and refine how errors are returned in your web applications.

Additionally, make sure to run a search through known data breach search engines such as BreachDirectory to ensure that your data is safe both during the day and the night and until the next time. See you in the next blog! 

Fuente: https://betterprogramming.pub/blind-sql-injection-threat-or-childs-play-6080d955a933

#sql 

What is GEEK

Buddha Community

Cómo Protegerse Contra La Inyección Ciega De SQL
Cayla  Erdman

Cayla Erdman

1594369800

Introduction to Structured Query Language SQL pdf

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

Cayla  Erdman

Cayla Erdman

1596441660

Welcome Back the T-SQL Debugger with SQL Complete – SQL Debugger

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:

  • Adding Breakpoints to control the execution pause of the T-SQL script at a specific statement allows you to check the debugging information of the T-SQL statements such as the values for the parameters and the variables.
  • Step Into is “navigate” through the script statements one by one, allowing you to check how each statement behaves.
  • Step Over is “execute” a specific stored procedure if you are sure that it contains no error.
  • Step Out is “return” from the stored procedure, function, or trigger to the main debugging window.
  • Continue executing the script until reaching the next breakpoint.
  • Stop Debugging is “terminate” the debugging session.
  • Restart “stop and start” the current debugging session.

#sql server #sql #sql debugger #sql server #sql server stored procedure #ssms #t-sql queries

Cómo Protegerse Contra La Inyección Ciega De SQL

Uno de los principales problemas en el mundo de las bases de datos es la inyección de SQL: prevalece hasta tal punto que incluso OWASP la enumera continuamente como la amenaza número 1 dirigida a las aplicaciones web . La inyección de SQL puede tener muchos tipos y uno de estos tipos es la inyección de SQL ciega: en esta publicación de blog, veremos cuán dañino puede ser un ataque de este tipo.

¿Qué es la inyección SQL? ¿Cuáles son sus Categorías?

Como ya le dijimos en algunas de nuestras publicaciones de blog anteriores , la inyección de SQL es el principal ataque dirigido a las bases de datos: una aplicación es vulnerable a la inyección de SQL cuando una entrada proporcionada por un usuario se envía directamente a una base de datos sin ser desinfectada y correctamente tratado.

Es muy importante entender las categorías de inyección SQL por un par de razones clave:

  • Los diferentes tipos de inyección SQL impactan en las aplicaciones web de diferentes maneras.
  • Algunos tipos de inyección SQL se pueden prevenir más fácilmente que otros.
  • Algunos tipos de inyección SQL dependen directamente de las características de nuestras aplicaciones web (por ejemplo, los resultados de un ataque de inyección SQL ciego exitoso dependen directamente de si nuestra aplicación web muestra errores o no).
  • Algunos tipos de ataques de inyección SQL tienen subtipos (piense en la inyección SQL ciega basada en el tiempo): estos subtipos también pueden hacer o deshacer un trato para una parte nefasta porque dependen directamente de un factor específico que, en este caso, no se puede controlar, por lo que son directamente - tiempo.

La inyección SQL tiene un par de categorías:

Como puede ver, no hay muchas categorías en las que caiga la inyección de SQL; sin embargo, mientras que la inyección de SQL clásica se usa con más frecuencia, cuando los ataques de inyección de SQL clásicos no funcionan, los atacantes generalmente recurren al lado ciego de SQL: intentan atacando aplicaciones con inyección ciega de SQL.

El Reino de la Inyección SQL Ciega

Think of your application as a castle. We know, this might seem at least a little bit odd, but bear with us. Now, imagine your web application as a castle. Done? Okay, imagine that a bunch of blind soldiers with spears are attacking it and their spears frequently miss the fortified defenses of the castle. What do you think — how much time the blind soldiers with spears have to spare to be done with your castle’s defenses? It will take a while, but the soldiers will eventually get through. That’s true — and once the soldiers get through, the treasures you store in your castle (the data inside of your web applications) are cactus — they will steal everything.

Soldiers are well-equipped, and even though they are blind, they will eventually perpetrate your defenses — oh, noes! That’s pretty much how blind SQL injection works in the real world, so let us give you another example:

  1. An attacker finds your web application to be vulnerable to a blind form of SQL injection by adding a single quote after a certain parameter — then your web application returns an error.
  2. An attacker keeps crafting SQL queries — none of them return any error. However, he quickly finds that if he executes one type of a query, the data inside of your web application shows on the screen, after he executes another — the data disappears. “Aha!”, — thinks the attacker. “Gotcha. Got a blind SQL injection flaw.”

As you might already notice, a blind SQL injection is such an attack that asks the database “questions” in a form of queries and tries to determine whether they are true or false based on the response on the web application. Blind SQL injection is most frequently detected by running queries like so:

If a web application returns a “positive” response (meaning that it returns a visible difference on a web page), the web application is susceptible to such an attack, while if an application is indifferent, it is probably not. In the first scenario, the attacker will know something’s up with your database and try to penetrate your defenses even further. And so the game begins — the attacker is trying to notice what kind of responses your web application is willing to return. A query returns a page with results — OK, he probes further, a query returns a blank page — hmmm… he changes the query and tries again. And so the game continues until all data that interests a nefarious party is extracted from your database. Yes, such kind of querying willtomar mucho tiempo (y esa es una de las cosas por las que la inyección ciega de SQL es más conocida), pero tenga en cuenta que el tiempo, por triste que sea, probablemente no detendrá a un atacante que tiene como objetivo dañar sus sistemas como tanto como sea posible o robar todos sus datos.

Some web applications might even filter the parts in GET or POST parameters meaning that they might “catch” single or double quotes being used, but that’s only one piece of the puzzle. Such a function is frequently a part of a web application firewall type of functionality — we have already discussed WAFs (short for Web Application Firewalls) in another article of ours, so we won’t go too much into detail, but keep in mind that web application firewalls deflect all kinds of attacks ranging from Denial of Service to, you guessed it, SQL injection. You can find a live example of a web application firewall by visiting the website of one of the biggest & fastest data breach search engines in the world — BreachDirectory — but for now, let’s get back to the topic.

Types of Blind SQL Injection

Hay dos tipos de inyección SQL ciega: basada en booleanos y basada en el tiempo. La inyección SQL ciega basada en booleanos depende del envío de una determinada consulta SQL a la base de datos para determinar si la consulta devuelve un resultado TRUEo FALSEal observar la respuesta de la aplicación, mientras que la inyección SQL basada en el tiempo depende del tiempo: una consulta que prueba un aplicación web para la inyección de SQL basada en tiempo ciego obligará a la base de datos a esperar un par de segundos antes de devolver una respuesta, y si la respuesta se devuelve después de que hayan pasado la cantidad exacta de segundos especificados, el atacante podrá determinar que la aplicación es susceptible a la inyección SQL ciega basada en el tiempo. Aquí hay un par de diferencias y similitudes clave entre los dos tipos:

Protección contra la inyección ciega de SQL

Protecting from a blind type of SQL injection, contrary to popular belief, does not take much skill or effort — it can be prevented using basic security measures. Yes, it’s as simple as that! We can accomplish that by using Prepared Data Objects (PDO) in PHP (they split the input provided by the user and the rest of the query, thus any kind of SQL injection is not possible), by using automated testing solutions that inform us whether or not our application is susceptible to SQLi, or, of course, using whitelist security controls — we, as developers, should have a habit of filtering and sanitizing every kind of parameter that somehow interacts with our data. By doing that we can put our web applications at the next security level both by protecting against all kinds of SQL injection attacks and other types of security issues.

Once we put our web applications at the next level of security, we must take care of the security of our own accounts too — we can run a search through BreachDirectory to see if any of our accounts are at risk and act according to the advice given to us. Once we do that, our accounts should be secure as well. Win — win!

Summary

Blind SQL injection is a type of SQL injection where an attacker cannot figure out how our web applications “think”, so instead they have to rely on the output a web application gives us or rely on time, depending on which method (boolean-based or time-based) is in use. When relying on boolean-based SQL injection, an attacker counts on the fact that the web application might look different than usual, while when using time-based SQL injection, the attacker heavily relies on time.

No matter what type of SQL injection is elected to use by the attacker, no type provides the attacker with a quick way to gain data — an attacker may literally spend hours, days, or even months gaining data of interest to him, but once the attack is successfully accomplished, it will usually be sold on the dark web for thousands of dollars to other nefarious parties, and the cycle will continue.

To protect against blind SQL injection, make sure to employ secure coding practices, do not forward user input straight into a database, and refine how errors are returned in your web applications.

Additionally, make sure to run a search through known data breach search engines such as BreachDirectory to ensure that your data is safe both during the day and the night and until the next time. See you in the next blog! 

Fuente: https://betterprogramming.pub/blind-sql-injection-threat-or-childs-play-6080d955a933

#sql 

Cayla  Erdman

Cayla Erdman

1596448980

The Easy Guide on How to Use Subqueries in SQL Server

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?

SQL Subqueries – What Are They?

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:

  • SQL subquery syntax depending on different subquery types and operators.
  • When and in what sort of statements one can use a subquery.
  • Performance implications vs. JOINs.
  • Common caveats when using SQL subqueries.

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.

Make SQL Subqueries That Are Self-Contained or Correlated

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:

  • isolate the subquery.
  • replace the reference to the outer query with a constant value.

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.

Make SQL Subqueries With 3 Possible Returned Values

Well, first, let’s think of what returned values can we expect from SQL subqueries.

In fact, there are 3 possible outcomes:

  • A single value
  • Multiple values
  • Whole tables

Single Value

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.

Multiple Values

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')

Whole Table Values

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:

  • All columns in the subquery should have unique names. Much like a physical table, a derived table should have unique column names.
  • ORDER BY is not allowed unless TOP is also specified. That’s because the derived table represents a relational table where rows have no defined order.

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

Ruth  Nabimanya

Ruth Nabimanya

1621850444

List of Available Database for Current User In SQL Server

Introduction

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

Get the list of database
Conclusion

#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