Query Languages & Databases Reference


Database Types Overview

TypeModelQuery LanguageExamplesBest ForAvoid When
Relational (RDBMS)Tables — rows/columns, fixed schemaSQLPostgreSQL, MySQL, SQL Server, Oracle, SQLiteOLTP, structured data, strong consistency, complex joinsSemi/unstructured data, rapidly changing schema
Key-ValueHash table of key → valueSimple GET/SET commandsRedis, Memcached, DynamoDBCaching, session storage, real-time lookupsQuerying by value, relationships between values
DocumentSelf-contained documents (usually JSON/BSON)Query objects / aggregation pipelinesMongoDB, CouchDB, Cloudant, DocumentDBFlexible schema, eCommerce, CMS, medical recordsComplex multi-doc joins, heavy multi-record transactions
Column (Wide-Column)Column families instead of rowsCQL (Cassandra Query Language)Cassandra, HBaseTime-series, IoT, write-heavy workloads, huge scaleComplex ad hoc queries, frequently changing schema
GraphNodes + edges (relationships)Cypher, Gremlin, SPARQLNeo4j, CosmosDB, ArangoDBSocial networks, fraud detection, recommendation engines, access mappingHigh-volume simple transactional workloads

SQL (Relational)

Core Statement Cheat Sheet

StatementDescriptionExample
SELECTRetrieve data from a tableSELECT column1, column2 FROM table_name;
FROMTable(s) to pull data fromSELECT * FROM table_name;
WHEREFilter rows on a condition (predicate)SELECT * FROM table_name WHERE condition;
ORDER BYSort result set (ASC default, DESC to reverse); can sort by column position numberSELECT * FROM table_name ORDER BY column1 DESC;
GROUP BYGroup rows sharing a column valueSELECT column1, COUNT(*) FROM table_name GROUP BY column1;
HAVINGFilter grouped data (like WHERE, but post-aggregation)... GROUP BY column1 HAVING COUNT(*) > 1;
LIMITRestrict number of rows returnedSELECT * FROM table_name LIMIT 10;
DISTINCTRemove duplicate values from a result setSELECT DISTINCT column1 FROM table_name;
INSERT INTOAdd new row(s) to a tableINSERT INTO table_name (col1, col2) VALUES (val1, val2);
UPDATEModify existing rows — always pair with WHERE or every row changesUPDATE table_name SET column1 = value1 WHERE condition;
DELETE FROMRemove rows — always pair with WHERE or the whole table emptiesDELETE FROM table_name WHERE condition;
CREATE TABLEDefine a new table’s schemaCREATE TABLE t (id INT PRIMARY KEY, name VARCHAR(50));
ALTER TABLEAdd/remove/modify columns (no parens, unlike CREATE)ALTER TABLE t ADD COLUMN email VARCHAR(100);
DROP TABLEDelete an entire table (structure + data)DROP TABLE table_name;
TRUNCATE TABLEFast-clear all rows, keep the schemaTRUNCATE TABLE table_name;

Aggregate Functions

FunctionDescriptionExample
COUNT()Number of rows / non-null valuesSELECT COUNT(*) FROM table_name;
SUM()Total of a numeric columnSELECT SUM(column1) FROM table_name;
AVG()Average valueSELECT AVG(column1) FROM table_name;
MAX()Highest valueSELECT MAX(column1) FROM table_name;
MIN()Lowest valueSELECT MIN(column1) FROM table_name;

Joins

JoinReturns
JOIN / INNER JOINOnly rows with matches in both tables
LEFT JOINAll rows from left table + matches from right (NULLs if none)
RIGHT JOINAll rows from right table + matches from left (NULLs if none)
FULL JOINAll 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)

ConstraintPurpose
PRIMARY KEYUniquely identifies each row; implies NOT NULL + unique
FOREIGN KEYReferences a primary key in another table, creating a relationship
NOT NULLColumn must always have a value
UNIQUENo 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

TypeNotes
INT / INTEGERWhole numbers
DECIMAL(p,s) / NUMERICExact fixed-precision numbers (money, etc.)
CHAR(n)Fixed-length string, padded to n
VARCHAR(n)Variable-length string, max n
TEXTLong unbounded string
DATE / DATETIME / TIMESTAMPDate/time values
BOOLEANTrue/false
BLOBRaw binary data

SQLite CLI (dot-commands)

Companion notes: Node-Express-Backend-Cheatsheet.md, Express-req-res-app-Reference.md.

sqlite3 mydb.db
CommandDescription
.tablesList all tables in the current database
.schema <table>Show the exact CREATE TABLE statement
.headers onShow column names above results
.mode columnAlign output into readable columns
.mode boxBordered table output (nicer for wide tables)
.exit / .quitLeave 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 like better-sqlite3 in 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)

CommandDescription
SET key valueStore a value under a key
GET keyRetrieve a value by key
DEL keyDelete a key
EXISTS keyCheck if a key exists (returns 1/0)
EXPIRE key secondsSet a TTL on a key
KEYS patternFind keys matching a pattern (e.g. user:*) — avoid in production, scans everything
INCR key / DECR keyAtomically increment/decrement a numeric value
HSET key field valueSet a field in a hash (object) stored under key
HGETALL keyGet all fields/values of a hash
LPUSH / RPUSH key valuePush onto a list (left/right)
LRANGE key start stopRead a range from a list
SADD key memberAdd to a set
TTL keyCheck remaining time-to-live on a key

Document — MongoDB (query syntax, JS shell / driver)

OperationExample
Find alldb.collection.find({})
Find with filterdb.collection.find({ status: "active" })
Find onedb.collection.findOne({ _id: ObjectId("...") })
Projection (limit fields)db.collection.find({}, { name: 1, email: 1, _id: 0 })
Insert onedb.collection.insertOne({ name: "Raul", city: "Toronto" })
Insert manydb.collection.insertMany([{...}, {...}])
Update onedb.collection.updateOne({ _id: id }, { $set: { status: "approved" } })
Update manydb.collection.updateMany({ status: "pending" }, { $set: { status: "reviewed" } })
Delete one/manydb.collection.deleteOne({...}) / deleteMany({...})
Sortdb.collection.find().sort({ createdAt: -1 })
Limitdb.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 pipelinedb.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.

StatementExample
Create keyspaceCREATE KEYSPACE ks WITH replication = {'class':'SimpleStrategy','replication_factor':3};
Create tableCREATE TABLE ks.users (id UUID PRIMARY KEY, name TEXT, city TEXT);
InsertINSERT INTO ks.users (id, name, city) VALUES (uuid(), 'Raul', 'Toronto');
SelectSELECT * FROM ks.users WHERE id = <uuid>;
UpdateUPDATE ks.users SET city = 'NYC' WHERE id = <uuid>;
DeleteDELETE 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)

OperationExample
Create nodeCREATE (a:Person {name: "Raul"})
Create relationshipMATCH (a:Person {name:"Raul"}), (b:Book {title:"SQL 101"}) CREATE (a)-[:READ]->(b)
Find nodeMATCH (a:Person {name: "Raul"}) RETURN a
Find relationshipsMATCH (a:Person)-[:FRIENDS_WITH]->(b:Person) RETURN a, b
FilterMATCH (a:Person) WHERE a.age > 21 RETURN a
Update propertyMATCH (a:Person {name:"Raul"}) SET a.city = "Buffalo"
Delete node + relsMATCH (a:Person {name:"Raul"}) DETACH DELETE a
Shortest pathMATCH p = shortestPath((a:Person)-[*]-(b:Person)) WHERE a.name="Raul" AND b.name="Mike" RETURN p

Wrangler and Cloudflare Workers

CommandFields / FlagsDescription
scaffoldingnpm create cloudflare@latestCreates a new Worker project, pick “Hello World example” → “Worker only” → TypeScript
npx wrangler loginnoneLogs wrangler into your Cloudflare account through the browser
npx wrangler whoaminoneChecks which Cloudflare account you’re logged into
npx wrangler dev--test-scheduledRuns the Worker locally on localhost:8787 with simulated KV/D1, the flag lets you trigger the cron by hand
trigger cron locallycurl http://localhost:8787/__scheduledRuns the scheduled handler right away instead of waiting for the cron (only works with --test-scheduled)
npx wrangler deploynoneUploads the Worker to Cloudflare, prints the workers.dev URL and the cron schedule
npx wrangler tailnoneStreams live logs from the deployed Worker, see the cron fire and any errors
npx wrangler typesnoneRegenerates the Env type from wrangler.jsonc, rerun this every time you change a binding
npx wrangler kv namespacecreate <NAME>, listCreates a KV bucket (prints the id for the config) / lists all of them with their ids
npx wrangler kv keylist --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.varsNAME=value per lineWhere 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 migrationscreate <db-name> <migration_name>Makes a new numbered .sql file in migrations/, never edit one that has already been applied
npx wrangler d1 migrationsapply <db-name> --local / --remoteRuns any migrations that haven’t run yet, local and remote are SEPARATE databases so do both
npx wrangler d1 migrationslist <db-name> --local / --remoteShows 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 honononeRouter 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 codeprepare("SQL ?").bind(value).first()prepare only BUILDS the query, nothing runs until .first(), .all(), or .run()
D1 in codedb.batch([stmt1, stmt2])Runs several statements in one trip as a transaction, either all succeed or none do
seehttps://developers.cloudflare.com/workers/wrangler/commands/Full list of every wrangler command and flag
seehttps://developers.cloudflare.com/d1/D1 docs, SQL details and the client API

Core Concepts Quick Reference

ConceptMeaning
Primary KeyColumn(s) that uniquely identify a row; can’t be null, can’t repeat
Foreign KeyColumn referencing another table’s primary key — creates the relationship
Entity-Relationship (ER) ModelDesign tool: entities → tables, attributes → columns
SchemaThe structure/blueprint of a table or database (columns, types, constraints) — not the data itself
NormalizationOrganizing tables to reduce redundancy (1NF → remove repeating groups, 2NF → remove partial dependency, 3NF → remove transitive dependency)
ACIDAtomicity, Consistency, Isolation, Durability — guarantees traditional RDBMS transactions provide
BASEBasically Available, Soft state, Eventual consistency — the tradeoff many NoSQL systems make instead of full ACID
OLTPOnline Transaction Processing — many small, fast read/write ops (what RDBMS is built for)
OLAPOnline Analytical Processing — complex queries over historical data (data warehousing)
IndexStructure that speeds up lookups on a column, at the cost of slower writes + extra storage
ShardingSplitting a dataset horizontally across multiple servers/nodes for scale
ReplicationCopying data across nodes for redundancy/availability
DaaSDatabase 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 joinsRelational (PostgreSQL/MySQL)
Sub-millisecond caching / session storeKey-Value (Redis)
Flexible schema, nested/varied recordsDocument (MongoDB)
Massive write throughput, time-series/IoT dataColumn (Cassandra)
Deep relationship traversal / connectionsGraph (Neo4j)
Local, zero-config, embedded storage for a small appSQLite

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