Monday, March 20, 2023
HomeHow ToHow to Use ChatGPT to Write SQL JOIN Queries

How to Use ChatGPT to Write SQL JOIN Queries

SQL JOINs are a fundamental aspect of relational database management and allow for the retrieval of data from multiple tables based on a specified condition. With the advent of advanced language models like OpenAI’s GPT, it is now possible to leverage their capabilities to write SQL JOIN queries efficiently and accurately.

In this article, we will explore the process of using ChatGPT to write SQL JOINs and provide a step-by-step guide on how to utilize AI for this purpose. We will be using dbForge Studio for SQL Server as a tool to verify and test SQL JOIN queries generated by ChatGPT. The Studio is a powerful database management solution that provides a user-friendly interface for executing SQL queries, making it easy to check the accuracy and efficiency of the queries generated by AI. Whether you’re a seasoned database developer or just starting to learn SQL, this article will provide valuable insights into the process of writing SQL JOINs with the help of the mentioned tools.

Download dbForge Studio for SQL Server

Contents

How ChatGPT can help SQL developers

ChatGPT can assist SQL developers in several ways:

Writing SQL queries: ChatGPT can help write SQL queries for tasks such as data retrieval, data manipulation, and database management.

Debugging SQL code: ChatGPT can assist in troubleshooting SQL code by providing suggestions for optimizing query performance, fixing syntax errors, and identifying potential issues.

Providing information on SQL syntax: ChatGPT can provide information on SQL syntax, keywords, and functions, making it easier for developers to write correct SQL code.

Offering query optimization tips: ChatGPT can provide tips on how to optimize SQL queries, such as using indexes, reducing complexity, and avoiding subqueries.

Generating reports: ChatGPT can generate reports based on SQL data, such as sales reports, customer reports, and inventory reports.

Overall, ChatGPT can help SQL developers become more efficient and productive by providing quick answers and support for various SQL-related tasks. Let us look at how it can help with quite complex queries such as JOINs.

Prerequisites

To effectively use ChatGPT to write SQL JOIN queries and verify them using dbForge Studio for SQL Server, the following prerequisites are required:

  • dbForge Studio for SQL Server. This advanced database management tool will be used to verify and test the SQL JOIN queries generated by ChatGPT. You can download it here.
  • ChatGPT Account. You will need an active account with OpenAI’s ChatGPT to interact with the language model and generate SQL JOIN queries.
  • AdventureWorks2019 database. This sample database will be used to demonstrate the process of writing SQL JOIN queries with ChatGPT and then verifying them using dbForge Studio for SQL Server.

With these prerequisites in place, you will be ready to follow the steps outlined in this article and learn how to effectively use ChatGPT to write SQL JOIN queries and verify them using dbForge Studio for SQL Server.

Download and install the AdventureWorks2019 database

  1. Download AdventureWorks2019.bak file from the official Microsoft website.
  2. Restore the AdventureWorks2019 database with the help of a database management tool such as SQL Server Management Studio or dbForge Studio for SQL Server. To do that, open the tool, connect to your SQL Server instance, and then follow the steps to restore the database from a backup file.
  3. Verify the database installation. Once the database has been restored, you can verify the installation by connecting to the database using the database management tool and browsing the database objects. You should see tables, views, stored procedures, and other database objects associated with the AdventureWorks2019 database.

Examples of SQL JOIN queries

Now that we have all the required prerequisites at hand, we can start using ChatGPT to write SQL JOIN queries and check them using dbForge Studio for SQL Server. Here’s how the process will work:

  1. Interact with ChatGPT: We will use ChatGPT to create all the types of SQL JOINS by providing it with information about the desired result. This can be done through an interaction with the language model, where we will provide it with the necessary details about the tables and columns we want to join and the result we want to achieve.
  2. Receive the SQL JOIN query: ChatGPT will generate the SQL JOIN query that meets the criteria specified. This query can be copied and pasted into dbForge Studio for SQL Server for execution.
  3. Run the SQL JOIN query in dbForge Studio for SQL Server: Having created the query, we will use dbForge Studio for SQL Server to execute the query against the AdventureWorks2019 database. This will allow us to verify the results of the SQL JOIN query and make sure that it returns the result we require.

INNER JOIN

Let us start with the most widespread and simple JOIN — INNER JOIN. An inner join returns only the rows from both tables where there is a match on the specified join condition. In other words, it returns only the intersecting data of both tables, discarding all the unmatched rows.

Suppose, we want to get a list of all customers along with their addresses and the orders they have placed. Let’s ask ChatGPT to assist us.

INNER JOIN - question to ChatGPT

Let’s now use dbForge Studio for SQL Server to execute the query that ChatGPT has created and confirm that it returns the results we require.

SELECT
  c.CustomerID
 ,p.FirstName + ' ' + p.LastName AS CustomerName
 ,a.AddressLine1
 ,a.city
 ,sp.Name AS StateProvince
 ,a.PostalCode
 ,o.SalesOrderID
 ,o.OrderDate
FROM Sales.Customer c
INNER JOIN Person.Person p
  ON c.PersonId = p.BusinessEntityID
INNER JOIN Person.BusinessEntityAddress bea
  ON p.BusinessEntityID = bea.BusinessEntityID
INNER JOIN Person.Address a
  ON bea.AddressID = a.AddressID
INNER JOIN Person.StateProvince sp
  ON a.StateProvinceID = sp.StateProvinceID
INNER JOIN Sales.SalesOrderHeader o
  ON c.CustomerID = o.CustomerID
Execute INNER JOIN created by ChatGPT in dbForge Studio for SQ: Server

The query has been successfully executed and outputs the desired result set.

LEFT JOIN

Let’s proceed to LEFT JOINS. Just a quick reminder — a LEFT JOIN in SQL is a type of join that returns all the rows from the left table (table1), and the matching rows from the right table (table2). If there is no match, NULL values will be output for the columns of the right table.

Now we will describe the desired result set to ChatGPT and ask it to write a query to get this result set. Suppose, we want to retrieve a list of all customers along with the number of orders they have ever placed.

Ask ChatGPT to create LEFT JOIN query

As anticipated, ChatGPT has generated a query using a LEFT JOIN. Let’s execute it using dbForge Studio for SQL Server to verify that it provides the expected outcome.

SELECT
  c.CustomerID
 ,p.FirstName + ' ' + p.LastName AS CustomerName
 ,COUNT(o.SalesOrderID) AS NumberOfOrders
FROM Sales.Customer c
LEFT JOIN Person.Person p
  ON c.PersonID = p.BusinessEntityID
LEFT JOIN Sales.SalesOrderHeader o
  ON c.CustomerID = o.CustomerID
GROUP BY c.CustomerID
        ,p.FirstName
        ,p.LastName
Run the LEFT JOIN query created by ChatGPT in dbForge Studio for SQL Server

RIGHT JOIN

Let us now ask ChatGPT to write a SELECT query with a RIGHT JOIN. A RIGHT JOIN in SQL works similarly to the LEFT JOIN and returns all the rows from the right table (table2) and the matching rows from the left table (table1). If there is no match, NULL values will be returned for the columns of the left table.

Suppose that we want to retrieve a result set that displays all vendors and all purchases made from these vendors in the AdventureWorks2019 database.

Question to ChatGPT - Create Right JOIN query

And again, let’s run the query created by ChatGPT in dbForge Studio for SQL Server — just to make sure it is working and returns the result set we expect.

SELECT
  v.Name AS VendorName
 ,p.OrderDate
 ,p.TotalDue
FROM [Purchasing].[PurchaseOrderHeader] p
RIGHT JOIN [Purchasing].[Vendor] v
  ON v.BusinessEntityID = p.VendorID
Execute the ChatGPT query in dbForge Studio for SQL Server

FULL OUTER JOIN

FULL OUTER JOIN is a type of join operation in relational databases where all rows from both tables being joined are included in the result set, regardless of whether there is a match in the other table. If there is a match, the rows from both tables are joined together. If there is no match, NULL values are used to fill in the columns from the missing table.

Let us ask ChatGPT to assist us with the FULL OUTER JOIN query.

ChatGPT: FULL OUTER JOIN

And now we check the query in dbForge Studio for SQL Server as we have done in previous examples.

SELECT
  *
FROM Sales.Customer
FULL OUTER JOIN Sales.SalesOrderHeader
  ON Sales.Customer.CustomerID = Sales.SalesOrderHeader.CustomerID;
FULL OUTER JOIN generated by ChatGPT run in dbForge Studio for SQL Server

CROSS JOIN

A CROSS JOIN, also known as a cartesian product, is a type of join operation in a relational database that combines every row from one table with every row from another table. The resulting table contains all possible combinations of rows from both tables. Let us ask ChatGPT to create a query to get all possible combinations of product categories and subcategories in the AdventureWorks2019 database.

CROSS JOIN created by ChatGPT

Let us now run the query in dbForge Studio for SQL Server to validate it.

SELECT
  pc.Name AS CategoryName
 ,psс.Name AS SubcategoryName
FROM Production.ProductCategory pc
CROSS JOIN Production.ProductSubcategory psс
Run the ChatGPT JOIN query in dbForge Studio for SQL Server

SELF JOIN

In SQL, a SELF JOIN is a regular join operation where a table is joined with itself. It is useful when we want to compare the data within a single table.

So, to receive a SELF JOIN, we need to ask ChatGPT to join a table to itself as if the table were two tables. Suppose we want obtain a list of all supervisors and their subordinates from the HumanResources.Employee table in the AdventureWorks2019 database, where the supervisor and subordinate share the same gender. Let us ask AI for help, shall we?

ChatGPT to create SELF JOIN

Great! The query is ready. Let’s now validate it in dbForge Studio and review the output.

SELECT 
    e1.Gender AS Gender,
    e1.JobTitle AS Supervisor,
    e2.JobTitle AS Subordinate
FROM 
    HumanResources.Employee e1
    FULL JOIN HumanResources.Employee e2
        ON e1.Gender = e2.Gender
WHERE 
    e1.OrganizationLevel = 1
    AND e2.OrganizationLevel <> 1
SELF JOIN created by ChatGPT in dbForge Studio for SQL Server

The examples above show that even if you are not an experienced SQL developer, you can still create complex queries involving JOINs. All you need to do is explain to the AI in detail the type of result you want to obtain or which tables to join, and it will take care of the task for you. It’s remarkable, isn’t it? As a result, complex database analysis and development are now becoming more accessible to the general public.

Can ChatGPT learn?

ChatGPT is a machine learning-based language model that is designed to learn and improve over time. It is trained on vast amounts of text data and uses that data to generate responses to user inputs. As ChatGPT interacts with users and receives feedback, it can continue to learn and adapt to user needs, improving its responses and becoming more accurate and effective over time.

When a user provides more context or details about their question or topic, ChatGPT can use that information to generate more relevant and accurate responses. By incorporating user feedback and additional information into its input data, ChatGPT can learn and adapt to the user’s needs, and generate more effective answers.

Conclusion

As a language model, ChatGPT can provide guidance and suggestions on how to construct complex SQL queries and JOINs, but it does not have direct access to a SQL database. It can help you with syntax, best practices, and general guidance on how to structure your queries for efficient execution. However, to create and run SQL queries of any complexity, you would need to use a database management system (such as SQL Server) and a GUI client to interact with this DBMS (such as dbForge Studio for SQL Server). If you are interested in how ChatGPT can help you write complex MySQL statements, feel free to read the Power Up Your MySQL Queries: How ChatGPT Can Help You Retrieve MySQL Data article.

If you are looking for a powerful and user-friendly database management tool, we recommend giving the Studio a try. With features like code completion, query profiling, and a visual query builder, it can significantly streamline your SQL Server development process. You can download a free trial of dbForge Studio for SQL Server from the Devart website to see how it can improve your workflow.

Download dbForge Studio for SQL Server
Helena Alexander
Helena Alexander
dbForge Team
RELATED ARTICLES

Whitepaper

Social

Topics

Products