How To Make Sql Queries
How to make SQL queries with Claude
In this notebook, we'll explore how to use Claude to generate SQL queries based on natural language questions. We'll set up a test database, provide the schema to Claude, and demonstrate how it can understand and translate human language into SQL queries.
Setup
First, let's install the necessary libraries and setup our Anthropic client with our API key.
Creating a Test Database
We'll create a test database using SQLite and populate it with sample data:
Generating SQL Queries with Claude
Now, let's define a function to send a natural language question to Claude and get the generated SQL query:
We'll retrieve the database schema and format it as a string:
CREATE TABLE EMPLOYEES ( id INTEGER name TEXT department TEXT salary INTEGER )
Now, let's provide an example natural language question and send it to Claude:
SELECT name, salary FROM EMPLOYEES WHERE department = 'Engineering';
Executing the Generated SQL Query
Finally, we'll execute the generated SQL query on our test database and print the results:
('Jane Smith', 75000)
('Emily Brown', 80000)
Don't forget to close the database connection when you're done: