Cheat sheet · Foundations
SQL and databases cheat sheet (SQL Server)
Opens with creditsFor students and early-career engineers learning SQL on Microsoft SQL Server, from the first SELECT to schema design, transactions, indexes and using SQL safely from application code. Every snippet is T-SQL, with SSMS, VS Code and sqlcmd as the tools.
Chapters
9 chapters · 77 concepts
1Relational model and your setupWhat a relational database is, the keys that connect tables, and the server, client and sample data you need before writing real queries.7 concepts
- 1Relational modelData stored in tables: each table describes one kind of thing, each row is one instance of it and each column is one attribute with a fixed type.
- 2Primary keyA column, or set of columns, whose value is unique and never NULL for every row, so it identifies exactly one row.
- 3Foreign keyA column that stores the primary key of a row in another table, declared with a constraint so the database rejects values that do not exist there.
- 4DDL, DML and DCLThe families of SQL statements: DDL defines structure (CREATE, ALTER, DROP), DML reads and changes rows (SELECT, INSERT, UPDATE, DELETE), DCL grants access…
- 5Command-line clientA terminal program that connects to the database server and runs SQL you type or pipe in: psql for PostgreSQL, mysql for MySQL, sqlcmd for SQL Server.
- 6SSMS and the VS Code MSSQL extensionSSMS is the Windows tool for querying and administering SQL Server.
- 7Sample databaseA ready-made database with realistic tables and thousands of rows that you load locally to practise on, such as pagila for PostgreSQL, sakila for MySQL or…
7 in this chapterOpen this chapter2Querying one tableSELECT from a single table: choosing columns, filtering rows, handling NULL, sorting, limiting and shaping results with expressions.9 concepts
- 1SELECT and FROMSELECT lists the columns or expressions you want back and FROM names the table they come from.
- 2WHEREWHERE keeps only the rows for which a condition is true, using comparisons, AND, OR, NOT, IN for a list, BETWEEN for an inclusive range and LIKE for simple…
- 3NULL and three-valued logicNULL means a value is missing or unknown.
- 4ORDER BYORDER BY sorts the result by one or more columns or expressions, ascending by default or DESC for descending.
- 5Limiting rowsReturning only the first N rows of a sorted result.
- 6DISTINCTDISTINCT removes duplicate rows from the result, comparing all selected columns together.
- 7CASE expressionCASE returns a value based on conditions checked in order, like if and else inside a query.
- 8String and date functionsBuilt-in functions for text (joining, trimming, changing case, extracting parts) and for dates (current time, adding intervals, truncating to a month).
- 9Logical order of a queryThe order a query is evaluated in, which differs from the order you write it: FROM and JOIN, then WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY and…
9 in this chapterOpen this chapter- Joins and set operationsCombining rows from several tables with joins, and combining whole result sets with UNION, INTERSECT and EXCEPT.8 conceptsOpens with credits
- Aggregation, subqueries and windowsSummarising rows with GROUP BY, nesting queries with subqueries and CTEs, and calculating rankings and running totals with window functions.11 conceptsOpens with credits
- Schema designTurning requirements into tables: entities and relationships, keys, normalisation, data types, constraints and views.9 conceptsOpens with credits
- Changing data safelyINSERT, UPDATE, DELETE and upserts, and the transactions, isolation levels and locks that keep concurrent changes correct.9 conceptsOpens with credits
- Indexes and query plansHow indexes make reads fast, how to read what the database actually did with EXPLAIN or an execution plan, and the habits that keep queries quick.10 conceptsOpens with credits
- SQL in applications and operationsUsing SQL safely from code, keeping schema changes under control, and the operational basics: pools, permissions, backups and where other kinds of database fit.9 conceptsOpens with credits
- NoSQL and MongoDBHow a document database compares with the relational model, using MongoDB: documents, queries mapped from SQL, embedding versus referencing, indexes and transactions, and JSON inside your own database.5 conceptsOpens with credits
- 10Glossary, A to ZEvery concept in the sheet and the smaller terms it uses, in one list.198 terms
About this sheet
Queries, design, indexes, transactions.
Related on Sefism
Picked from the other libraries by shared topics.
Roadmaps
See allBest practices
See all- PostgreSQL Best PracticesDesign, index, query and run PostgreSQL well: data types, constraints, EXPLAIN, zero-downtime migrations, pooling, transactions, backups and roles.
- MongoDB Best PracticesModel, index, query and run MongoDB well: access-pattern schemas, validation, the ESR rule, aggregation limits, write concern, transactions, drivers and security.
- Data Pipeline Best PracticesHow to build data pipelines you can re-run, test and trust: idempotent tasks, orchestrator hygiene, layered transformations, data tests, freshness, ownership and monitoring.
Checklists
See allProject structures
See all- NestJS project structureFor people who want a structured TypeScript backend with clear rules about where code goes. Every feature is a Nest module that owns its controller, service, DTOs, entities and tests, so the app grows by adding folders, not by stretching old ones. The tree follows one orders API from nest new to a codebase a whole team can run for years.
- FastAPI project structureA typed Python API for an orders app, built the way the FastAPI docs and the official full stack template lay it out: one
apppackage, a router per feature, Pydantic schemas at the edges, services in the middle and SQLAlchemy models with Alembic migrations underneath. For students who have finished the FastAPI tutorial and want to know where the second, tenth and fiftieth file go. - Django project structureFor students building their first serious Python web app or API with Django, and for the team that keeps it running years later. The project is a thin "config" package plus one Django app per business area (accounts, catalog, orders, core), each owning its models, services, views, API, migrations and tests. Settings come from validated environment variables, and the tree grows from the tutorial layout to CI, containers, observability and enforced module boundaries.
Career questions
See all- Should I use PostgreSQL or MongoDB for my project?For most student and startup projects, PostgreSQL is the safer default: relational data, joins, constraints and transactions fit most apps, and it handles JSON and vector search too. MongoDB is a good fit when your data is naturally document-shaped and varies a lot, or your team already knows it well. Model your data first, then choose.
- Should I use Firebase or Supabase for my app?Both let you ship an app fast with auth, a database, storage and hosting-style services. Supabase is built on PostgreSQL, so it suits relational data and SQL skills you will reuse anywhere. Firebase is a mature Google platform with a document database and strong mobile tooling. Choose by your data shape, your platform, and how much you want to learn transferable database skills.
- Do I need a vector database for my AI project?Often not. For a student project or a small app, a vector extension on a database you already use (such as pgvector in PostgreSQL), or even an in-memory index, is enough. A dedicated vector database earns its place with very large collections, heavy query traffic, or features like advanced filtering and multi-tenancy at scale.
Cheat sheets
See all- MongoDB cheat sheetDocuments, modelling, indexes, aggregation.
- Choosing the right database cheat sheetSQL, document, cache, search, vector and more.
- Vector databases cheat sheetEmbeddings, similarity metrics, ANN indexes, filtering, hybrid search, reranking, RAG chunking, pgvector, dedicated stores and evaluation.
Work with me
Stuck on something specific?
Writing only gets you so far. If you want an answer to your situation rather than the general case, book a session and we will work through it together. Sessions are free for approved Sefism members, and a few slots open each week.
- 1:1 Mentorship
- Fresh Graduate Mentorship
- Career Guidance
Brand deals, promos and partnerships: tauseeffayyaz@gmail.com