2026-08-31 00:00 Status: Tags: SQL NoSQL Data Base Data Science MongoDB Redis Cassandra Neo4j Cypher Query Languages Reference Guide Important Command Line
Query Languages & Databases Reference
Database Types Overview
| Type | Model | Query Language | Examples | Best For | Avoid When |
|---|---|---|---|---|---|
| Relational (RDBMS) | Tables — rows/columns, fixed schema | SQL | PostgreSQL, MySQL, SQL Server, Oracle, SQLite | OLTP, structured data, strong consistency, complex joins | Semi/unstructured data, rapidly changing schema |
| Key-Value | Hash table of key → value | Simple GET/SET commands | Redis, Memcached, DynamoDB | Caching, session storage, real-time lookups | Querying by value, relationships between values |
| Document | Self-contained documents (usually JSON/BSON) | Query objects / aggregation pipelines | MongoDB, CouchDB, Cloudant, DocumentDB | Flexible schema, eCommerce, CMS, medical records | Complex multi-doc joins, heavy multi-record transactions |
| Column (Wide-Column) | Column families instead of rows | CQL (Cassandra Query Language) | Cassandra, HBase | Time-series, IoT, write-heavy workloads, huge scale | Complex ad hoc queries, frequently changing schema |
| Graph | Nodes + edges (relationships) | Cypher, Gremlin, SPARQL | Neo4j, CosmosDB, ArangoDB | Social networks, fraud detection, recommendation engines, access mapping | High-volume simple transactional workloads |
SQL (Relational)
Core Statement Cheat Sheet
| Statement | Description | Example |
|---|---|---|
SELECT | Retrieve data from a table | SELECT column1, column2 FROM table_name; |
FROM | Table(s) to pull data from | SELECT * FROM table_name; |
WHERE | Filter rows on a condition (predicate) | SELECT * FROM table_name WHERE condition; |
ORDER BY | Sort result set (ASC default, DESC to reverse); can sort by column position number | SELECT * FROM table_name ORDER BY column1 DESC; |
GROUP BY | Group rows sharing a column value | SELECT column1, COUNT(*) FROM table_name GROUP BY column1; |
HAVING | Filter grouped data (like WHERE, but post-aggregation) | ... GROUP BY column1 HAVING COUNT(*) > 1; |
LIMIT | Restrict number of rows returned | SELECT * FROM table_name LIMIT 10; |
DISTINCT | Remove duplicate values from a result set | SELECT DISTINCT column1 FROM table_name; |
INSERT INTO | Add new row(s) to a table | INSERT INTO table_name (col1, col2) VALUES (val1, val2); |
UPDATE | Modify existing rows — always pair with WHERE or every row changes | UPDATE table_name SET column1 = value1 WHERE condition; |
DELETE FROM | Remove rows — always pair with WHERE or the whole table empties | DELETE FROM table_name WHERE condition; |
CREATE TABLE | Define a new table’s schema | CREATE TABLE t (id INT PRIMARY KEY, name VARCHAR(50)); |
ALTER TABLE | Add/remove/modify columns (no parens, unlike CREATE) | ALTER TABLE t ADD COLUMN email VARCHAR(100); |
DROP TABLE | Delete an entire table (structure + data) | DROP TABLE table_name; |
TRUNCATE TABLE | Fast-clear all rows, keep the schema | TRUNCATE TABLE table_name; |
Aggregate Functions
| Function | Description | Example |
|---|---|---|
COUNT() | Number of rows / non-null values | SELECT COUNT(*) FROM table_name; |
SUM() | Total of a numeric column | SELECT SUM(column1) FROM table_name; |
AVG() | Average value | SELECT AVG(column1) FROM table_name; |
MAX() | Highest value | SELECT MAX(column1) FROM table_name; |
MIN() | Lowest value | SELECT MIN(column1) FROM table_name; |
Joins
| Join | Returns |
|---|---|
JOIN / INNER JOIN | Only rows with matches in both tables |
LEFT JOIN | All rows from left table + matches from right (NULLs if none) |
RIGHT JOIN | All rows from right table + matches from left (NULLs if none) |
FULL JOIN | All rows from both tables regardless of match |
SELECT column1, column2
FROM table1
JOIN table2 ON table1.column = table2.column;- Joins work off a primary key in one table matching a foreign key in another.
- For 3+ tables: join A→B on their shared column first, then join the result to C.
Constraints (used inside CREATE TABLE / ALTER TABLE)
| Constraint | Purpose |
|---|---|
PRIMARY KEY | Uniquely identifies each row; implies NOT NULL + unique |
FOREIGN KEY | References a primary key in another table, creating a relationship |
NOT NULL | Column must always have a value |
UNIQUE | No duplicate values allowed in the column |
DEFAULT <value> | Value used automatically if none is provided |
CHECK (<condition>) | Restricts allowed values (e.g. CHECK (age >= 18)) |
Common Data Types
| Type | Notes |
|---|---|
INT / INTEGER | Whole numbers |
DECIMAL(p,s) / NUMERIC | Exact fixed-precision numbers (money, etc.) |
CHAR(n) | Fixed-length string, padded to n |
VARCHAR(n) | Variable-length string, max n |
TEXT | Long unbounded string |
DATE / DATETIME / TIMESTAMP | Date/time values |
BOOLEAN | True/false |
BLOB | Raw binary data |
SQLite CLI (dot-commands)
Companion notes: Node-Express-Backend-Cheatsheet.md, Express-req-res-app-Reference.md.
sqlite3 mydb.db| Command | Description |
|---|---|
.tables | List all tables in the current database |
.schema <table> | Show the exact CREATE TABLE statement |
.headers on | Show column names above results |
.mode column | Align output into readable columns |
.mode box | Bordered table output (nicer for wide tables) |
.exit / .quit | Leave the shell |
PRAGMA table_info(<table>); | One row per column: name, type, nullable, default |
Every statement in the CLI needs a trailing
;— a...>prompt instead of a result means you forgot it. The CLI and something likebetter-sqlite3in Node both point at the same db file — changes in one are visible in the other. CLI is for manual inspection/fixes; app code should always use?placeholders for untrusted input.
NoSQL Family Reference
Key-Value — Redis (CLI commands)
| Command | Description |
|---|---|
SET key value | Store a value under a key |
GET key | Retrieve a value by key |
DEL key | Delete a key |
EXISTS key | Check if a key exists (returns 1/0) |
EXPIRE key seconds | Set a TTL on a key |
KEYS pattern | Find keys matching a pattern (e.g. user:*) — avoid in production, scans everything |
INCR key / DECR key | Atomically increment/decrement a numeric value |
HSET key field value | Set a field in a hash (object) stored under key |
HGETALL key | Get all fields/values of a hash |
LPUSH / RPUSH key value | Push onto a list (left/right) |
LRANGE key start stop | Read a range from a list |
SADD key member | Add to a set |
TTL key | Check remaining time-to-live on a key |
Document — MongoDB (query syntax, JS shell / driver)
| Operation | Example |
|---|---|
| Find all | db.collection.find({}) |
| Find with filter | db.collection.find({ status: "active" }) |
| Find one | db.collection.findOne({ _id: ObjectId("...") }) |
| Projection (limit fields) | db.collection.find({}, { name: 1, email: 1, _id: 0 }) |
| Insert one | db.collection.insertOne({ name: "Raul", city: "Toronto" }) |
| Insert many | db.collection.insertMany([{...}, {...}]) |
| Update one | db.collection.updateOne({ _id: id }, { $set: { status: "approved" } }) |
| Update many | db.collection.updateMany({ status: "pending" }, { $set: { status: "reviewed" } }) |
| Delete one/many | db.collection.deleteOne({...}) / deleteMany({...}) |
| Sort | db.collection.find().sort({ createdAt: -1 }) |
| Limit | db.collection.find().limit(10) |
| Comparison ops | $gt, $gte, $lt, $lte, $ne, $in, $nin — e.g. { age: { $gte: 18 } } |
| Logical ops | $and, $or, $not — e.g. { $or: [{a:1},{b:2}] } |
| Aggregation pipeline | db.collection.aggregate([{ $match: {...} }, { $group: { _id: "$field", total: { $sum: 1 } } }]) |
Column — Cassandra (CQL)
Syntax intentionally looks SQL-like, but partitioning/clustering keys matter a lot more than in RDBMS.
| Statement | Example |
|---|---|
| Create keyspace | CREATE KEYSPACE ks WITH replication = {'class':'SimpleStrategy','replication_factor':3}; |
| Create table | CREATE TABLE ks.users (id UUID PRIMARY KEY, name TEXT, city TEXT); |
| Insert | INSERT INTO ks.users (id, name, city) VALUES (uuid(), 'Raul', 'Toronto'); |
| Select | SELECT * FROM ks.users WHERE id = <uuid>; |
| Update | UPDATE ks.users SET city = 'NYC' WHERE id = <uuid>; |
| Delete | DELETE FROM ks.users WHERE id = <uuid>; |
Cassandra queries generally must include the partition key in
WHERE— it’s not built for arbitrary ad hoc filtering the way SQL is.
Graph — Neo4j (Cypher)
| Operation | Example |
|---|---|
| Create node | CREATE (a:Person {name: "Raul"}) |
| Create relationship | MATCH (a:Person {name:"Raul"}), (b:Book {title:"SQL 101"}) CREATE (a)-[:READ]->(b) |
| Find node | MATCH (a:Person {name: "Raul"}) RETURN a |
| Find relationships | MATCH (a:Person)-[:FRIENDS_WITH]->(b:Person) RETURN a, b |
| Filter | MATCH (a:Person) WHERE a.age > 21 RETURN a |
| Update property | MATCH (a:Person {name:"Raul"}) SET a.city = "Buffalo" |
| Delete node + rels | MATCH (a:Person {name:"Raul"}) DETACH DELETE a |
| Shortest path | MATCH p = shortestPath((a:Person)-[*]-(b:Person)) WHERE a.name="Raul" AND b.name="Mike" RETURN p |
Wrangler and Cloudflare Workers
| Command | Fields / Flags | Description |
|---|---|---|
| scaffolding | npm create cloudflare@latest | Creates a new Worker project, pick “Hello World example” → “Worker only” → TypeScript |
npx wrangler login | none | Logs wrangler into your Cloudflare account through the browser |
npx wrangler whoami | none | Checks which Cloudflare account you’re logged into |
npx wrangler dev | --test-scheduled | Runs the Worker locally on localhost:8787 with simulated KV/D1, the flag lets you trigger the cron by hand |
| trigger cron locally | curl http://localhost:8787/__scheduled | Runs the scheduled handler right away instead of waiting for the cron (only works with --test-scheduled) |
npx wrangler deploy | none | Uploads the Worker to Cloudflare, prints the workers.dev URL and the cron schedule |
npx wrangler tail | none | Streams live logs from the deployed Worker, see the cron fire and any errors |
npx wrangler types | none | Regenerates the Env type from wrangler.jsonc, rerun this every time you change a binding |
npx wrangler kv namespace | create <NAME>, list | Creates a KV bucket (prints the id for the config) / lists all of them with their ids |
npx wrangler kv key | list --binding=<BINDING> --remote, get "<key>" --binding=... | Looks at what’s actually stored in KV, swap --remote for --local to check the dev copy |
npx wrangler secret put | <NAME> | Stores a secret on the deployed Worker (never in code), shows up as env.<NAME> |
.dev.vars | NAME=value per line | Where secrets live for local dev, MUST be in .gitignore |
npx wrangler d1 create | <db-name> | Creates a D1 (SQLite) database, prints the database_id for the config |
npx wrangler d1 migrations | create <db-name> <migration_name> | Makes a new numbered .sql file in migrations/, never edit one that has already been applied |
npx wrangler d1 migrations | apply <db-name> --local / --remote | Runs any migrations that haven’t run yet, local and remote are SEPARATE databases so do both |
npx wrangler d1 migrations | list <db-name> --local / --remote | Shows which migrations have been applied, first thing to check when a row or table “doesn’t exist” |
npx wrangler d1 execute | <db-name> --local --command "SELECT * FROM counters" | Runs raw SQL against the database, great for checking what’s actually in there |
npm install hono | none | Router for Workers, gives you Express style app.get() / app.post() plus cors() middleware |
| config: cron | "triggers": { "crons": ["*/5 * * * *"] } | Goes in wrangler.jsonc, calls the scheduled handler on that schedule |
| config: KV | "kv_namespaces": [{ "binding": "NAME", "id": "..." }] | Connects a KV bucket, the binding name is what you use in code as env.NAME |
| config: D1 | "d1_databases": [{ "binding": "DB", "database_name": "...", "database_id": "..." }] | Connects a D1 database, same deal, env.DB in code |
| D1 in code | prepare("SQL ?").bind(value).first() | prepare only BUILDS the query, nothing runs until .first(), .all(), or .run() |
| D1 in code | db.batch([stmt1, stmt2]) | Runs several statements in one trip as a transaction, either all succeed or none do |
| see | https://developers.cloudflare.com/workers/wrangler/commands/ | Full list of every wrangler command and flag |
| see | https://developers.cloudflare.com/d1/ | D1 docs, SQL details and the client API |
Core Concepts Quick Reference
| Concept | Meaning |
|---|---|
| Primary Key | Column(s) that uniquely identify a row; can’t be null, can’t repeat |
| Foreign Key | Column referencing another table’s primary key — creates the relationship |
| Entity-Relationship (ER) Model | Design tool: entities → tables, attributes → columns |
| Schema | The structure/blueprint of a table or database (columns, types, constraints) — not the data itself |
| Normalization | Organizing tables to reduce redundancy (1NF → remove repeating groups, 2NF → remove partial dependency, 3NF → remove transitive dependency) |
| ACID | Atomicity, Consistency, Isolation, Durability — guarantees traditional RDBMS transactions provide |
| BASE | Basically Available, Soft state, Eventual consistency — the tradeoff many NoSQL systems make instead of full ACID |
| OLTP | Online Transaction Processing — many small, fast read/write ops (what RDBMS is built for) |
| OLAP | Online Analytical Processing — complex queries over historical data (data warehousing) |
| Index | Structure that speeds up lookups on a column, at the cost of slower writes + extra storage |
| Sharding | Splitting a dataset horizontally across multiple servers/nodes for scale |
| Replication | Copying data across nodes for redundancy/availability |
| DaaS | Database as a Service — e.g. Amazon RDS, Google Cloud SQL, IBM Db2 on Cloud |
Choosing a Database (Quick Decision Table)
| If you need… | Reach for… |
|---|---|
| Strong consistency, structured data, complex joins | Relational (PostgreSQL/MySQL) |
| Sub-millisecond caching / session store | Key-Value (Redis) |
| Flexible schema, nested/varied records | Document (MongoDB) |
| Massive write throughput, time-series/IoT data | Column (Cassandra) |
| Deep relationship traversal / connections | Graph (Neo4j) |
| Local, zero-config, embedded storage for a small app | SQLite |
References
- SQL for Data Science with Python
- Companion notes:
Command Line Reference.md,Node-Express-Backend-Cheatsheet.md,Express-req-res-app-Reference.md,DADSD - Module 1 - Getting Started with SQL & Relational Databases.md