Open In App

How to Use SQL Statements in MS Excel?

Last Updated: 01 Nov, 2023

S

Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Most Excel spreadsheets need you to manually insert data into cells before analyzing it or performing calculations using formulae or other functions. You may use Excel to get data from a big data source, such as an Access database, an SQL Server database, or even a huge text file. SQL statements in Excel allow you to connect to an external data source, parse fields or table contents, and import data without having to manually enter the data.

After importing external data using SQL commands, you may sort, analyze, and conduct any necessary computations. Here, we will be discussing how to execute SQL statements in MS Excel. For this, an open-source package called ‘xlwings’ is required. So, before we begin with the process of running SQL queries in MS Excel, we will have to install xlwings. For running SQL queries in MS Excel using xlwings, having Windows OS and Python is a must.

Install Xlwings

Make sure you have installed pip for Python beforehand. If not, refer to this GeeksforGeeks link. Once you have installed pip, open your Command Prompt type pip install xlwings, and hit Enter. Once this command is executed completely, type xlwings add-in install and hit Enter. Now, open Excel, and you’ll find xlwings section added.

SQL Queries in Excel

Step 1: Creation of Tables in Excel.

For the execution of SQL queries in Excel, in this article, two tables have been created in Excel (same workbook) and will be used for demonstration of the same. The two tables are – Employee Table and Department Table, as depicted below:

Table 1: Employee Table.

Employee-Table.

Employee Table

Table 2: Department Table.

Department-Table

Department Table

Step 2: Write the SQL query in Excel.

Type in the SQL query to be executed in Excel. (You may first Merge and center the cells and then type in the SQL query). 
Note: When only one table is being referred to, use ‘a’/’A’ for referring to it. If there are two tables, for example, when Joins are used, use ‘a’/’A’ for the first table and use ‘b’/’B’ for referring to the second table

SQL-Query-sample.

SQL Query

Step 3: Running the SQL query in Excel.

For executing the SQL query, type in =sql( in a new cell, where you need the retrieved data to be displayed. Then, click on the Insert Function option, displayed to the left of the Formula Bar.

insert-function

Executing Query

On clicking the Insert Function option, a dialog box appears, which requires 2 inputs – Query and Tables. For the Query input, select the SQL query cell (above step) or simply manually type in the query to be executed.

For the Tables input, hold and drag the entire table to be used for the SQL query. If there is more than one table, add the table(s) in a similar fashion in the Tables input. After this, click on the Ok button, and presto, the data is retrieved!

function-argument-shown

Output: Now you can see the output of the SQL Query. 

sql-query-output

output

More Sample SQL Queries in Excel

  • SELECT STATEMENT SQL: The SELECT statement is used to get information from a database. The information returned is saved in a result table known as the result set.

Select statement syntax: SELECT Age FROM a

select-query

Output

SELECT Name, Gender FROM a 

selecting-name

Output

  • WHERE CLAUSE SQL: To filter records, use the WHERE clause. It is used to extract only records that meet a predefined requirement.

Where clause syntax: SELECT * FROM a WHERE Gender = ‘Female’    

where-condition-applied

Output

  • OR OPERATOR: The OR operators are used to filter records based on several criteria. If any of the conditions separated by OR is TRUE, the OR operator shows a record.

Or operator syntax: SELECT * FROM a WHERE Gender = ‘MALE’ OR Age < 40     

or-operator

Output

  • NOT OPERATOR: If the condition(s) is NOT TRUE, the NOT operator shows a record.

Not operator syntax: SELECT * FROM a WHERE NOT Gender = ‘Female’     

not-operator

Output

  • MIN() FUNCTION: The MIN() method returns the column with the lowest value.

          Min function syntax: SELECT MIN(Age) FROM a 

It shows the data of minimum age only

Output

  • AVERAGE FUNCTION SQL: AVG() returns the average value of a numerical column.

          Avg function syntax: SELECT AVG(Age) FROM a

It shows the data of average age only.

Output

  • GROUP BY STATEMENT: The SQL GROUP BY clause is used in conjunction with the SELECT statement to group identical data. In a SELECT statement, the GROUP BY clause comes after the WHERE clause and before the ORDER BY clause.

Group By statement syntax: SELECT AVG(Salary) AS Avg_Sal, Gender FROM a GROUP BY Gender 

group-by-query

Output

  • SQL INNER JOIN: The INNER JOIN keyword selects records from both tables that have matching values.  

Inner join syntax: SELECT a.Name,a.Dept,b.D_Name,b.D_City FROM an INNER JOIN b ON a.Dept=b.D_Name

applying-inner-join

Output



S

News
Improve
Discuss
Do you want to advertise with us?Click here to know more

VBA Multiple (Nested) If Statements in Excel

article_img
VBA in Excel stands for Visual Basic for Applications, which is Microsoft's programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. What decision-making reasoning do you often use in your Excel worksheets? In most circumstances, you would test your condition using an IF formula and return one value if the condition is met and another value if it is not. You can nest multiple IFs inside of one another to assess more than one condition and return different values based on the outcomes. Where to Put the VBA Code in Excel?In the Microsoft Excel tabs, select the Developer Tab. Initially, the Developer Tab may not be available.  The Developer Tab can be enabled easily by a two-step process : Right-click on any of the existing tabs at the top of the Excel window.Now select Customize the Ribbon from the pop-down menu. In the Excel Options Box, check the box Developer to enable it and click on OK. Now, the Developer Tab is visible. Now click on the Visual Basic option in the Developer tab and make a new module to write the program using the Select Case statement.Developer  -> Visual Basic -> Tools -> Mac
Read More

Editing Excel Macros in Excel

article_img
Excel Macro is a set of actions that can be recorded, saved, used multiple times. This feature saves us a lot of time when dealing with repetitive tasks and huge data sets. We can always make changes to an existing Macro in Excel. There are two ways to record and run macros: Excel Commands Excel Visual Basic for Applications(VBA).1. Copying a Macro Code We can reuse the existing macro code while creating new Macros. For example, if you have existing macros created using the record function, we can reuse the code to write new macros. To open the code follow the below steps: Select Tools --> Macros --> Visual Basic Editor. Copy code from the existing macros(use Command + C) and paste(use Command + V) in the new macro2. Renaming a Macro Follow the below steps to rename a Macro in Excel: Select Tools --> Macros --> Visual Basic Editor. Select name on the left plane.Edit the name.3. Deleting a Macro Follow the below steps to delete a macro in Excel: Select Tools --> Macros --> Macros... Select the macro to be deleted. Click on the minus(-) symbol at the bottom.Select yes to delete the macro.
Read More

Best Microsoft Excel High-Paying Jobs with Excel Skills in 2024

article_img
Are you ready to unlock a world of opportunities with Microsoft Excel? In today’s data-driven job market, mastering Excel is essential for launching a successful career, whether you're a fresher or an experienced professional. In this article, we will cover the high-paying Excel jobs available in 2024, including crucial roles like data analyst, business analyst, and many more. We'll explore the qualifications needed for these positions, along with salary estimations to help you understand your earning potential. Whether you’re looking for Excel jobs for freshers or seasoned professionals, we’ll also dive into options for Excel freelancing jobs and work-from-home jobs in Excel. Equip yourself with the knowledge to excel in your career and take the first step toward a lucrative future!Best Microsoft Excel High-Paying Jobs with Excel Skills in 2024Table of ContentWhy choose a career in ExcelWhy Excel Skills Are Essential for Your CareerEssential Excel Skills Required to Boost Your Resume Best Microsoft Excel High-Paying JobsFinancial AnalystsData AnalystAdministrative Assistant Accountants Project ManagersManagement ConsultantRetail Store ManagersBusiness Analyst Market Research A
Read More

Excel VLOOKUP Function - Excel Guide for Beginners

article_img
How to do Vlookup in Excel - Quick StepsPrepare Your DataEnter the VLOOKUP Formula >>Press EnterUse a Cell Reference for Flexibility Copy the Formula for Multiple RowsThe VLOOKUP function is one of the most widely used tools in Excel for looking up and retrieving data from a table. Whether you’re working with a single sheet or multiple workbooks, VLOOKUP allows you to search for a value in one column and return a related value from another. If you're new to Excel or still getting the hang of formulas, this guide is for you. We will cover everything from the basics of how VLOOKUP works to practical examples that show how to search data across sheets, troubleshoot common issues, and master the VLOOKUP formula for any task.Excel VLOOKUP FunctionWhat is the VLOOKUP Function in ExcelThe term VLOOKUP stands for Vertical Lookup. It is designed to search for a specific value in the first column of a table (lookup column) and retrieve corresponding data from a different column in the same row.Syntax of VLOOKUP FormulaVLOOKUP(lookup_value, table_array, col_index_num, [range_lookup])Arguments:1. lookup_value: The value you want to search for (e.g., a specific ID, name, or product code).
Read More

AI in Excel: Top 20 Excel AI Tools in 2025 (Free/Paid)

article_img
The integration of AI in Excel is transforming the way professionals manage, analyze, and visualize data. Whether you're handling large datasets, performing financial analysis, or automating repetitive tasks, AI-powered tools can significantly improve efficiency and accuracy. In 2025, advanced Excel AI tools are making complex tasks easier by offering features like data cleaning, predictive analytics, smart automation, and AI-driven insights.In this guide, we’ve gathered a list of the top 20 Excel AI tools for 2025 that are reshaping how users interact with Excel.Table of ContentBest AI Tool in Excel: Top Picks for 2025Top 10 Free Excel AI Tools in 2025Top 10 Excel AI ToolsAI in Excel: OverviewIn Excel, an AI tool (Artificial Intelligence tool) refers to an add-in or extension that leverages artificial intelligence to enhance your spreadsheet experience. These tools can automate tasks, improve data analysis, and generally make you more productive.Excel has always been a powerful tool for data analysis, but with the integration of AI tools, it has transformed into a smarter, more intuitive platform.Best AI Tool in Excel: Top Picks for 2025Explore the below AI tools designed for auto
Read More

How to Use Select Case Statement in Excel VBA?

article_img
VBA in Excel stands for Visual Basic for Applications which is Microsoft's programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. In this article, we are going to discuss how to use Select Case Statement in Excel VBA. Select Case Statement of Excel VBA The select case in VBA is like a detective that investigates an expression by checking it against different scenarios listed as Case Statements, each with its own conditions. When a scenario matches the expression, it's like solving a piece of the puzzle, and the corresponding code linked to that scenario is activated. Importantly, once a match is found, the detective stops investigating and moves on to executing the discovered code. Yet, if none of the scenarios match, it's like the detective hitting a dead end. In this situation, the code associated with the Case Else statement comes into play, offering a default solution or outcome. Syntax of the Select Case Statement of Excel VBAThe VBA Select Case Statement shares similarities with the Switch Case construct found in programming languages such as Java, C#, and PHP. In Excel VBA, this statement helps
Read More

A

How to Use for Each Loop in Excel VBA?

A For Each loop is used to execute a statement or a set of statements for each element in an array or collection. Syntax: For Each element In group [ statements ] [ Exit For ] [ statements ] Next [ element ] The For...Each...Next statement syntax has the following three parts: PartDescriptionelement Required (Must be mentioned). Variable is used to iterate through the elements of the collection or array. For collections, the element can only be a Variant variable, a generic object variable, or any specific object variable. For arrays, the element can only be a Variant variable.groupRequired(Must be mentioned). Name of an object collection or array (except an array of user-defined types).statementOptional (May or may not be mentioned). One or more statements are executed on each item in the group. There are 4 basic steps to writing a For Each Next Loop in VBA: Declare a variable.Write the For Each Line with the variable and collection references.Add line(s) of code to repeat for each item in the collection.Write the Next line to terminate the loop. The For…Each block is entered if there is at least one element in the group. Upon entering the loop,
Read More

A

How to Use Do While Loop in Excel VBA?

article_img
A Do…While loop is used when we want to repeat certain set of statements as long as the condition is true. The condition may be checked at the starting or at the end of the loop Flowchart: Uses of Do-While loop: The Do While loop is used in two ways: Do…while loop which checks the condition at the STARTING of the loop.Do…while loop which checks the condition at the END of the loop. Syntax 1: Do While condition [statements] [Exit Do] [statements] Loop Syntax 2: Do While [statements] [Exit Do] [statements] Loop conditionImplementing a Do While loop: Follow the below steps to implement a Do-While loop: Step 1: Define a Macro Private Sub Demo_Loop() End Sub Step 2: Define variables j=2 i=1 Step 3: Write Do While Loop. You can write condition at the beginning or at the end Do While i < 5 Step 4: Write statements to be executed in loop msgbox "Table of 2 is : " & (j*i) i=i+1 Step 5: End loop. Now let's take a look at some of the examples. Example 1: Do…while loop which checks the condition at the STARTING of the loop. The below example uses Do…while loop to check the condition at the starting of the loop. The statements inside the loop are executed, only if the condition is True
Read More

How to Use For Next Loop in Excel VBA?

article_img
If you are familiar with the programming you must have an idea of what a loop is, In computer programming, a loop is a sequence of statements that are repeated until a specific condition is satisfied. In Excel VBA the "For Next" loop is used to go through a block of code a specific number of times. Syntax: For counter = start to end [step count] [code block to execute] statement 1 statement 2 statement 3 . . statement n Next [counter] Here we can use the counter or any other variable to run them as many times as we need. Example: When you are displaying numbers from 1 to 10 you may want to set the value of a variable to 1 and display it 10 times, increasing its value by 1 on each loop iteration. The same logic is used in VBA. We specify how many times we have to run the loop, and then specify what code should our loop execute each time the loop runs. A loop has 3 parts the first one is an initialization, the second is the condition under which the loop runs, and the last is increment or decrement. The flow of the control in for loop:The For step is executed first. This step allows you to initialize any loop control variables and increment the step counter variable.Then the second
Read More

How to use Binomial Distribution in Excel?

article_img
The BINOM.DIST Function is ordered under Excel Statistical capabilities. It works out the binomial distribution likelihood for the number of triumphs from a predetermined number of preliminaries. This binomial distribution Excel guide will tell you the best way to utilize the capability, bit by bit. The binomial distribution is a factual measure that is regularly used to show the likelihood of a particular number of victories happening from a particular number of free preliminaries. The two structures utilized are: The Probability Mass Function: Ascertains the likelihood of there being precisely x triumphs from n autonomous preliminaries.The Cumulative Distribution Function: Computes the likelihood of there being all things considered x triumphs from n autonomous preliminaries. In the monetary examination, the BINOM.DIST capability can help in finding out, for instance, the likelihood of distributing a smash hit book from a scope of books to be distributed by an organization. Formula for Binomial Distribution =BINOM.DIST(number_s,trials,probability_s,cumulative) The BINOM.DIST utilizes the accompanying contentions: Number_s (required argument): This is the number of accomplishments
Read More
three90RightbarBannerImg