Skip to content

SQL in Basthon ​

Open the console or the notebook in SQL (URL parameter kernel=sql). Examples are in the gallery, and the special commands added by Basthon are described on the SQL: what Basthon adds page.

SQLite's special commands (dot commands) are available: .tables and .schema describe the database, .export downloads it (.help lists them all, see the API page).

What you can do ​

Querying a given database ​

A database (*.db, *.sqlite) or a script (*.sql) attached with the module URL parameter is loaded when the page opens: students query it straight away, create other tables and make joins (try it):

sql
SELECT nom, v.marque, pays
FROM voitures AS v
JOIN constructeurs AS c ON c.marque = v.marque;

A query that returns no row still shows the names of the columns (post).

Learning to write queries ​

A notebook of the gallery progresses step by step on the database of a school library (authors, books, loans): selection and sorting, aggregate functions, GROUP BY and HAVING, joins of three tables, subqueries, updates, and a bar chart drawn with substr (try it):

sql
SELECT nom AS auteur, COUNT(*) AS emprunts,
       substr('■■■■■■■■■■■■■■■■■■■■', 1, COUNT(*)) AS diagramme
FROM emprunts
JOIN livres ON emprunts.id_livre = livres.id
JOIN auteurs ON livres.id_auteur = auteurs.id
GROUP BY auteurs.id
ORDER BY emprunts DESC;

In the console, a script creates a database of the solar system and invites you to query it (try it).

Integrity constraints ​

SQLite's foreign key constraints are on (try it). A notebook goes through every constraint: primary key, NOT NULL, UNIQUE, CHECK, foreign key, and STRICT tables that enforce types (try it).

Exploring and exporting the database ​

.tables and .schema describe the database, .export and .dump download it (see above, try it, post).

Completion ​

The Tab key completes SQLite's keywords and functions (in the case typed: sel gives select), the tables and their columns, including through an alias (after FROM students s, s. offers the columns of students), and the .tables, .schema… commands.

Files and modules ​

The SQL kernel has no filesystem: extra files are not available. The open button (or the module URL parameter) loads, however, a database (*.db or *.sqlite), which is opened, or a script (*.sql), which is run.

Downloading a file ​

The database is downloaded with .export (in the binary .db format) or .dump (in SQL format), see above.