brew install SQLite
.sqlite3 intro.db
.shell clear
.help
: List available dot commands..tables
: List tables in the database..show
: Display current settings..databases
: Show the path to the database file..schema
: Display the schema of the database.create table
.
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
username TEXT NOT NULL UNIQUE,
email TEXT,
age INTEGER,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
PRIMARY KEY
: uniquely identifies each row in the table.NOT NULL
: requires that the column must have a value.UNIQUE
: ensures that no two rows have the same value in this column.DEFAULT
: specifies a default value for the column if none is provided during insertion..sql
extension (e.g., intro.sql
)..read
command:sqlite3 intro.db
.read intro.sql
ALTER TABLE
: modifies the structure of an existing table.status
column to the users
table.sql
ALTER TABLE users
ADD COLUMN status TEXT;
DROP TABLE
: deletes a table.sql
DROP TABLE users;
CREATE TABLE
ALTER TABLE
DROP TABLE
INSERT INTO
: adds new rows to a table.sql
INSERT INTO users (name, username)
VALUES ('Caleb Curry', 'calcur123');
NOT NULL
columns are required.SELECT
: retrieves data from one or more tables.users
table.sql
SELECT * FROM users;
WHERE
: filters rows based on a condition.LIMIT
: limits the number of rows returned.UPDATE
: modifies existing data in a table.SET
: specifies the columns to update and their new values.WHERE
: specifies which rows to update.sql
UPDATE users
SET email = 'newemail@gmail.com'
WHERE id = 1;
DELETE FROM
: removes rows from a table.WHERE
: specifies which rows to delete.sql
DELETE FROM users
WHERE id = 2;
sql
CREATE TABLE posts (
id INTEGER PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
title TEXT NOT NULL,
body TEXT NOT NULL
);
REFERENCES
: establishes a foreign key relationship to the users
table.JOIN
.sql
SELECT *
FROM posts
JOIN users ON posts.user_id = users.id;
posts
and users
tables where the user_id
in posts
matches the id
in users
.sql
SELECT p.body, u.username
FROM posts p
JOIN users u ON p.user_id = u.id;
sql
CREATE VIEW posts_info AS
SELECT p.body, u.username
FROM posts p
JOIN users u ON p.user_id = u.id;
SELECT * FROM posts_info;