C. Titus Brown
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- tags: datalab,sqlite --- # SQLite Hands On - Thursday, Jan 19, 2023 CTB [toc] ## Running SQLite ### Installing SQLite3 locally For Windows users who want to try things out locally: * go to https://www.sqlite.org/download.html * find "Precompiled Binaries for Windows" * download and install [sqlite-tools-win32-x86-3400100.zip](https://www.sqlite.org/2022/sqlite-tools-win32-x86-3400100.zip) For Mac OS X and Linux computers, sqlite3 _should_ come installed with Python. On my Mac, `sqlite3` works to run it. ### Using a binder [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/ngs-docs/2023-ggg298-sourmash-compare/stable?urlpath=rstudio) This will create an RStudio Server running in the cloud. To get to a command line, go to Terminal... To run sqlite3, run `sqlite3 database.sql` at the terminal! ## Introducing SQLite3 ## A Hands-On Introduction to SQL with SQLite! SQLite is the amazing little embedded database that could! It comes with Python, it’s on every Apple device ever made, and it just … plain … works. Really, really well. You might be interested in this session (generally) and SQLite (specifically) if any or all of the following apply - * you have too much spreadsheet/dataframe-like data to fit easily in memory; * you’ve heard about SQL but never really used it; * you want to access the same data from multiple programming languages (like Python and R); * you are naturally curious; In this session I’ll develop a simple database for storing information about a personal book collection, and we’ll explore it together. I’ll show - * how to design a simple SQL schema * how to add data into the database with Python, and how to retrieve it * how to explore database contents from the command line ## Some initial hands-on SQLite is an open source database that you can use to store data on disk and interact with/retrieve that data in simple and also complex ways. * it's very fast in many circumstances! * it stores structured data! * it is very "safe" in that it is a very robust way to store data * I have not found it to be super disk space efficient but that can be tuned ### Creating a database with a simple schema Here's a simple schema: ```sql= PRAGMA foreign_keys = ON; CREATE TABLE owners ( id INTEGER PRIMARY KEY, name TEXT NOT NULL ); CREATE TABLE books ( owner_id INTEGER, author TEXT NOT NULL, title TEXT NOT NULL, isbn TEXT NOT NULL, FOREIGN KEY (owner_id) REFERENCES owners (id) ); ``` * every database consists of one or more tables (as well as views and other things); * each table is like a dataframe * tables can be linked - see `owner_id` above! * pragmas configure runtime information - here we are telling sqlite3 to obey foreign key constraints (more on that in a bit) To start with this, run `sqlite3 library.db` at the command line. You should end up with a `sqlite>` prompt. Then copy/paste the above schema definitions. ### Adding information - when all goes well At the sqlite prompt, run ```sql= insert into owners (name) values ('titus'); insert into owners (name) values ('hannah'); select * from owners; ``` * owner_id is automatically generated * this is a fast primary key to be used for various retrieval operations; guaranteed to be unique! And now add: ```sql= INSERT INTO books (owner_id, author, title, isbn) VALUES (1, 'F. Scott Fitzgerald', 'Great Gatsby', '0-1-2-3'); INSERT INTO books (owner_id, author, title, isbn) VALUES (1, 'Charles Dickens', 'A Tales of Two Cities', '0-1-3-5'); INSERT INTO books (owner_id, author, title, isbn) VALUES (2, 'Ernest Hemingway', 'The Sun Also Rises', '5-4-6-7'); SELECT * FROM books; ``` et voila! You can change the output format for selects with `.mode`, e.g. `.mode markdown`. You can get my books with: ```sql= SELECT * from owners,books WHERE owners.name='titus' AND books.owner_id=owners.id; ``` This is called an "inner join" because you are showing tables only where the rows match. You can also do an outer join, or a cross-product: ```sql= SELECT * FROM owners, books; ``` You can also do summary operations across groups - ```sql= select owners.name,COUNT(books.title) FROM owners,books WHERE owners.id=books.owner_id GROUP BY owners.id; ``` and also do sorting - ```sql= SELECT name FROM owners ORDER BY name ASC; ``` and lots of other things. SQL is its whole own world! ### When the schema stops you Try running: ```sql= DELETE FROM owners WHERE name='titus' ``` it should fail with >Runtime error: FOREIGN KEY constraint failed (19) Same with: ```sql= UPDATE books SET owner_id=8; ``` Basically, SQLite can provide what's called "referential integrity" to databases, preventing you from "breaking" the schema structure. ## A few more advanced things ### Looking at a database You can retrieve the schema from a database with `.schema`. This is pretty handy :laughing: ### Talking to a database SQLite3 is embedded. No background server is needed! That means that you can run the following Python code and there's no need to have anything else running: ```python= import sqlite3, pprint # get a database connection db = sqlite3.connect('library.db') # get a cursor (a way to interact with database - can have multiple of these) c = db.cursor() # run a SQL query c.execute('SELECT * from books,owners WHERE books.owner_id=owners.id') # retrieve results for row in c: pprint.pprint(row) ``` You can have multiple independent cursors, so you can run different queries with different cursors - if you want to run nested queries, you'll need two. sqlite3 does support transactional isolation, so you can have one connection/set of cursors with a different view of the database than another; think simultaneous bank transactions... SQLite3 does have support for R, but I don't know R much if at all :) ## Fun facts and thoughts about SQLite You can manage millions of rows, hundreds of GBs of data, etc. with SQLite. SQLite is a pretty good way to store data in an efficient, query-able way that is cross-language. SQLite can be used to store "blobs" of data (images, for example) but it somewhat defeats the purpose of it to have "opaque" objects that can't be compared/sorted/matched/displayed.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully