Why does this Sqlite3 query not work using the magical function "%sql" in Jupyter Notebook?

230 Views Asked by At

I am having an error while trying to run a query with the magic function %sql in jupyter notebook

My query:

%sql SELECT "Elementary, Middle, or High School" FROM chicago_public_schools_data LIMIT 1;

Error:

  • sqlite:///socioeconomic.db (sqlite3.OperationalError) near "or": syntax error [SQL: SELECT Elementary, Middle, or High School FROM chicago_public_schools_data LIMIT 1;] (Background on this error at: https://sqlalche.me/e/20/e3q8)

I'm sure that column name is matching, controlled by selecting all columns, or printing with 'df.columns'.

Index(['School_ID', 'Elementary, Middle, or High School','Street_Address'......

Don't know how can I solve this.

I tried to use (") instead of ('), or use %%sql instead of %sql

Here is an example screenshot from my data: enter image description here

Here is a screenshot from the command line with my query, and example query. I'm getting output with my query in the command line. So my syntax works well on the command line but not on jupyter notebook. enter image description here

1

There are 1 best solutions below

0
Bibhav On BEST ANSWER

Using the cell command:
Parsing for a single line doesn't seem to be good in the jupyter notebook.
I recommend you make use of the cell command every time you execute the SQL command using the magic function in jupyter notebook.

%%sql
SELECT "Elementary, Middle, or High School" FROM chicago_public_schools_data LIMIT 5;

This works and %sql doesn't because using %sql parses the line as:

SELECT Elementary, Middle, or High School FROM chicago_public_schools_data LIMIT 5;

This will raise errors.