BLACK FRIDAY EXTRA SAVINGS EVENT - EXTENDED
START FREE

Convert SQL Code to Python

Hello Community,

Can someone let me know if it’s possible to convert to MS SQL, (that is T-SQL) to Python?

If it is easily possible, can someone let me know if there are any tools that I can use to convert SQL to Python?

Cheers

Carlton

Hi Carlton
I usually use SQLALchemy for that. It’s possible to apply raw SQL queries or use it’s own expressions
check it out:
https://docs.sqlalchemy.org/en/13/core/tutorial.html
I hope it’s what you are looking for :slight_smile:

Hi mimnet,

I’m looking at the link but I’m not seeing any examples.

For example, can I use the link to convert the following SQL to Python?

    SELECT
      Country.CountryName
     ,COUNT(SalesDetails.SalePrice) AS CarsSold --simply counting the number of cars sold
     ,SubQuery.expr1 AS TotalCarsSold -- simply totalling ALL the cars sold
    FROM (SELECT
             COUNT(SalesDetails.SalesDetailsID) AS expr1
           FROM Data.SalesDetails) SubQuery
        ,Data.Country
         INNER JOIN Data.Customer
           ON Country.CountryISO2 = Customer.Country
         INNER JOIN Data.Sales
           ON Customer.CustomerID = Sales.CustomerID
         INNER JOIN Data.SalesDetails
           ON Sales.SalesID = SalesDetails.SalesID
    GROUP BY Country.CountryName
            ,SubQuery.expr1

I don’t quite understand your question. If you want to use SQL query inside python code you don’t need to use any transformations. You use a raw SQL query and that’s it.

That is, if you are working with a Postgres database, you use the psycopg2 library, and use the same query as if you were writing it directly when accessing the database

Oooooooooh…I see… the penny has dropped (as we say in England). I think you’re saying that I could simply use the example I showed in Python itself, correct?

Using SQLalchemy, you can establish a connection to the SQL server through python, and then send your SQL query to your instance and capture the result back into python.
It’s a really great module and something I would advise you to learn for your skill set, you won’t regret it :slight_smile:

In short you import SQLalchemy engine, setup your connection string and open it, send your command and capture the result.
You then will possibly want to loop through your SQLalchemy object and drop the data into pandas so you can easily work on it.

Oh wow!

I will check this out for sure

@carlton - have you seen this Dataquest course? Would it help? I thought it was quite interesting.

https://app.dataquest.io/m/256/querying-sqlite-from-python

Hi Zachary,

Thanks for reaching out.

I will also check this out.

Cheers
Carlton

1 Like

Hiii @carlton,

I hope you have solved the problem. if you did, can you please share or guide me a way to the solution i am facing the same problems.

Thank you.