Microsoft Fabric Star Schema: Views, Functions and Stored Procedures
Introduction
A Microsoft Fabric star schema gives reports a consistent way to group and filter measures. In this DP-600 lesson, you will choose where to create views, functions and stored procedures, define the grain of a sales fact table, and preserve customer history with a type 2 dimension.
Learning objectives
- Create and choose between views, functions and stored procedures in a warehouse or a lakehouse SQL analytics endpoint.
- Design a star schema (facts, dimensions, grain, keys) for a lakehouse or a warehouse.
- Decide when and how to denormalize.
- Enrich data with calculated columns, lookup tables and a date dimension.
- Recognise what each engine supports (T-SQL write support, Delta tables, medallion layers).
1. What you can create where
| Capability | Warehouse | Lakehouse SQL analytics endpoint | Lakehouse (Spark) |
|---|---|---|---|
| Tables | Create and modify tables with supported T-SQL | Read registered Delta tables, including eligible shortcuts | Create and write Delta tables |
| Views | Yes | Yes | Spark SQL temporary and persisted views |
| Functions | Inline table-valued functions and supported scalar UDFs | Inline table-valued functions and supported scalar UDFs | Spark built-in functions and supported UDFs |
| Stored procedures | Yes, with DML | Yes, but they cannot write to lakehouse tables | No (use notebooks) |
| Cross-database queries | Yes, three-part names inside the workspace | Yes | Spark across lakehouses |
The central rule: the SQL analytics endpoint of a lakehouse is read-only for table data, but you can still add objects such as views, functions, stored procedures that only read, and security rules. A warehouse supports table DML and transactions that span multiple statements and tables. Check the Fabric T-SQL surface area before reusing SQL Server scripts.
2. SQL views for reusable queries
A view is a stored SELECT statement. It stores no data and is evaluated at query time.
Why use a view:
- Abstraction: hide joins and renamed columns behind a stable contract.
- Security: expose a subset of columns or rows; combined with SQL permissions, a user may query the view but not the base table.
- Reuse: one definition used by many reports and semantic models.
- Compatibility: present business-friendly names to Power BI.
CREATE VIEW dbo.vw_SalesEnriched
AS
SELECT s.OrderID,
s.OrderDate,
c.CustomerName,
c.Region,
p.ProductName,
s.Quantity * s.UnitPrice AS SalesAmount
FROM dbo.FactSales AS s
JOIN dbo.DimCustomer AS c ON c.CustomerKey = s.CustomerKey
JOIN dbo.DimProduct AS p ON p.ProductKey = s.ProductKey;Points to remember:
- A standard view is not materialized. If a costly join is repeated frequently and a scheduled result is acceptable, persist the result in a table with a stored procedure or pipeline. Fabric Warehouse does not support materialized views.
- Direct Lake on OneLake reads Delta-backed tables. Direct Lake on SQL can use a SQL view through DirectQuery fallback when it is enabled. Prefer a physical Delta table when the model should stay on the Direct Lake path.
- Views in a lakehouse endpoint read Delta tables written by Spark; new tables appear after metadata sync.
Example. Contoso wants sales analysts to see customer names but not the raw email column. The data engineer creates vw_CustomerPublic that omits Email, and grants the analysts permission to connect and select from the view. Test access as an analyst, including an attempted read of the base table. Broad workspace, item or OneLake grants can expose another path to the source.
3. Functions
T-SQL user-defined functions return a scalar value or a table.
- Scalar function: returns one value, for example a fiscal year from a date.
- Inline table-valued function (iTVF): returns a table from a single SELECT; behaves like a parameterised view and optimizes well.
- Use an inline table-valued function for reusable tabular queries. For scalar UDFs used in a query against user tables, check that Fabric can inline the function in that query.
CREATE FUNCTION dbo.fn_SalesByRegion (@Region varchar(50))
RETURNS TABLE
AS
RETURN
(
SELECT OrderDate, SUM(SalesAmount) AS Total
FROM dbo.vw_SalesEnriched
WHERE Region = @Region
GROUP BY OrderDate
);Use a function when you need parameterised, reusable logic that can be composed inside a SELECT. Use a view when no parameter is needed. Functions can also support row-level security predicates (the predicate function that a security policy applies).
4. Stored procedures for Warehouse loads
A stored procedure is a named, parameterised batch of T-SQL that can contain control flow, transactions and DML. In a warehouse it is the standard tool for repeatable transformation steps and loads.
For this Warehouse example, assume the staged batch has one row per non-null customer ID and the load runs serially in its own transaction. The target has a generated CustomerKey bigint IDENTITY, one current row per customer, and datetime2(6) validity columns. The pipeline supplies one UTC effective timestamp for the batch, later than any current version it changes. City and customer name are the tracked attributes.
CREATE PROCEDURE dbo.usp_LoadDimCustomer
@EffectiveAt datetime2(6)
AS
BEGIN
BEGIN TRY
BEGIN TRANSACTION;
UPDATE d
SET IsCurrent = 0, ValidTo = @EffectiveAt
FROM dbo.DimCustomer AS d
JOIN stg.Customer AS s ON s.CustomerID = d.CustomerID
WHERE d.IsCurrent = 1
AND (s.City <> d.City
OR (s.City IS NULL AND d.City IS NOT NULL)
OR (s.City IS NOT NULL AND d.City IS NULL)
OR s.CustomerName <> d.CustomerName
OR (s.CustomerName IS NULL AND d.CustomerName IS NOT NULL)
OR (s.CustomerName IS NOT NULL AND d.CustomerName IS NULL));
INSERT INTO dbo.DimCustomer
(CustomerID, CustomerName, City, ValidFrom, ValidTo, IsCurrent)
SELECT s.CustomerID, s.CustomerName, s.City, @EffectiveAt, NULL, 1
FROM stg.Customer AS s
WHERE NOT EXISTS (
SELECT 1
FROM dbo.DimCustomer AS d
WHERE d.CustomerID = s.CustomerID AND d.IsCurrent = 1
);
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
THROW;
END CATCH;
END;The update and insert commit together. An unchanged row keeps its current key on a retry of the same batch. For late-arriving sales, look up the dimension version whose validity interval includes the sale timestamp, using ValidFrom <= SaleTime AND (SaleTime < ValidTo OR ValidTo IS NULL). Keep each fact linked to that version's surrogate key. Validate one current row per customer and check for overlapping validity intervals.
Typical uses: loading and merging dimensions, populating a fact table, truncating and reloading a staging schema, and being called by a pipeline Stored procedure activity or a Script activity. A procedure gives the load one entry point. Grant EXECUTE as needed and verify the permissions on any objects it references.
| Object | Stores data | Takes parameters | Can modify data | Typical use |
|---|---|---|---|---|
| View | No | No | No | Reusable, secured SELECT |
| Inline table-valued function | No | Yes | No | Parameterised reusable query |
| Scalar function | No | Yes | No | Reusable calculation |
| Stored procedure | No | Yes | Yes (warehouse) | Load and transformation logic |
| Table (CTAS) | Yes | n/a | n/a | Materialised result |
CREATE TABLE AS SELECT (CTAS) and SELECT ... INTO materialise a query result in a warehouse; they are the answer when a heavy view must become a physical table.
Worked example: view, function or procedure?
Statement. A retailer needs (1) a semantic-model-friendly object that joins sales to products, (2) the ability for a report to pass a region and get totals, and (3) a nightly job that rebuilds FactSales from staging and updates a watermark table, all inside one warehouse.
Reasoning. (1) No parameter and no data change: a view. (2) A parameter with a SELECT result: an inline table-valued function. (3) Needs DML on two tables and ideally one transaction: a stored procedure called from a pipeline.
Solution. Create vw_SalesProduct, fn_SalesByRegion and usp_LoadFactSales.
Why other choices are worse. A view cannot accept a parameter or modify data; a function cannot perform DML on tables; a stored procedure cannot be selected from in a FROM clause, so it is awkward for reports.
5. Star schema
A star schema organises an analytical model around fact tables (measurable events) surrounded by dimension tables (descriptive context).
- Fact table: one row per event at a declared grain (for example one row per order line). Contains foreign keys to dimensions and numeric measures (quantity, amount). Additive measures can be summed across all dimensions; semi-additive measures, such as account balances, cannot be summed over time; non-additive (ratios) are recomputed.
- Dimension table: one row per entity or tracked entity version, with descriptive attributes used for filtering and grouping.
- Surrogate key: an artificial integer key in a dimension, independent of the source system's business key. It supports slowly changing dimensions and joins efficiently. Fabric Warehouse supports
bigint IDENTITYwithout a custom seed or increment. In Spark, persist a stable key mapping across batches. A row number ormonotonically_increasing_id()generated separately on each batch is not a durable cross-batch key. - Date dimension: one row per calendar day with year, quarter, month, week, fiscal calendar and holiday flags; essential for time intelligence later in the semantic model.
5.1 Slowly changing dimensions (SCD)
| Type | Behaviour | When |
|---|---|---|
| Type 1 | Overwrite the old value | History not needed (typo fix) |
| Type 2 | New row with validity dates and a current flag | Track history (customer moves city) |
| Type 3 | Extra column for the previous value | Limited history, rare |
5.2 Why a star schema?
- Simple one-to-many relationships let dimensions filter facts at a consistent grain.
- Matches the way Power BI engines compress and filter data. Narrow fact tables can reduce the amount of data the engine needs to scan or load.
- Avoids ambiguity: filters flow from dimension to fact.
5.3 Snowflake, and what to avoid
A snowflake schema normalises dimensions into sub-dimensions (Product → Subcategory → Category). It saves storage but adds joins and complexity. In Fabric, where storage is cheap and the semantic model prefers fewer joins, flatten into one dimension unless there is a good reason. Avoid one huge "flat file" table for everything: it duplicates descriptive text across millions of rows and makes the model harder to maintain.
Example. Adventure Works records line items. Grain: one row per order line. FactSales has DateKey, ProductKey, CustomerKey, Quantity, NetAmount. DimProduct carries ProductName, Subcategory, Category, Colour. DimDate is generated once for 2015–2035. Customer address changes are tracked with SCD type 2.
6. Designing in a lakehouse and in a warehouse
Medallion architecture organises layers: bronze (raw, as ingested), silver (cleansed, conformed), gold (modelled, business-ready star schema). Layers can be separate lakehouses, schemas or workspaces.
In a lakehouse, you build the star schema as Delta tables with Spark or Dataflows Gen2, then expose them to SQL through the endpoint and to Power BI through Direct Lake. Use OPTIMIZE to compact small files when the workload benefits. VACUUM reclaims obsolete files after the retention window. Choose retention that preserves the history and concurrent reads you need.
In a warehouse, you build tables with T-SQL (CTAS, INSERT, stored procedures). Warehouse tables are stored as Delta in OneLake, so Spark and shortcuts can read them as well. The warehouse is the right home when the team is SQL-centric and needs transactions.
| Decision | Lakehouse | Warehouse |
|---|---|---|
| Build the gold star schema with Spark/PySpark | Yes | No |
| Build with T-SQL and stored procedures | Read-only endpoint | Yes |
| Store raw unstructured files | Yes, in Files | Use a lakehouse or external storage |
| Multi-table T-SQL write transactions | Unavailable through the SQL endpoint | Supported |
| Share to Spark and SQL with one copy | Yes | Yes (Delta in OneLake) |
7. Denormalization
Denormalization deliberately duplicates or flattens data to avoid joins and speed up reads. In analytics it is normal in the gold layer.
Common uses include flattening a product hierarchy into one dimension and building a separate monthly aggregate for a dashboard. A degenerate dimension such as an order number can stay on the fact when it has no separate descriptive attributes. Keep mutable customer attributes in a dimension unless you intentionally need a snapshot on each fact.
Costs: redundant storage, update anomalies when the source attribute changes, and larger fact tables. Choose the degree of normalization by layer and measure the effect on maintenance and queries.
Worked example: flattening a product hierarchy
Statement. DimProduct joins to DimSubcategory, which joins to DimCategory. The semantic model slicers filter by category and subcategory only. Query times are acceptable, but the model has three tables and a confusing field list. Product categories change at most once a year.
Reasoning. The hierarchy is small and stable, and users only need the descriptive names. Flattening removes two relationships and two tables without meaningful redundancy cost.
Solution. Create DimProduct containing ProductName, Subcategory, Category through a view or a transformation, and relate it directly to the fact.
Why not keep the snowflake. It adds joins and relationships with no benefit. Why not put category on the fact table. It would repeat text millions of times and make updates costly.
8. Enriching data with new columns or tables
Enrichment adds value to existing data.
- Derived columns:
SalesAmount = Quantity * UnitPrice,OrderYear,IsLateDeliverycomputed in a view, a CTAS, a dataflow or Spark (withColumn). - Lookup/reference tables: map country codes to regions, SKU to product family, or postal code to sales territory; load them from a file or a shortcut and join in the gold layer.
- Date and time dimensions: generate with a numbers table, a supported date series, or Spark. Fabric Warehouse does not support recursive CTEs.
- Bridge and mapping tables for many-to-many relationships (customers and accounts).
- External enrichment: shortcuts to another domain's tables, or a join to master data.
Where to compute? Compute as early as it is stable and reusable: in the warehouse or lakehouse rather than in each report. Keep volatile, context-dependent logic (YTD, ratios) as DAX measures in the semantic model, because they depend on filters.
For the notebook example, use a schema-enabled lakehouse with existing silver and gold schemas. Run it against an isolated target because overwrite replaces the target table.
from pyspark.sql import functions as F
df = spark.read.table("silver.sales")
gold = (df.withColumn("SalesAmount", F.col("Quantity") * F.col("UnitPrice"))
.withColumn("OrderYear", F.year("OrderDate")))
gold.write.mode("overwrite").format("delta").saveAsTable("gold.FactSales")Comparison: choosing where logic lives
| Situation | Best place |
|---|---|
| Reusable join exposed to many reports | View |
| Parameterised reusable query | Inline table-valued function |
| Scheduled rebuild with DML and transactions | Stored procedure in a warehouse |
| Heavy transformation of files at scale | Spark notebook in a lakehouse |
| Business logic that depends on user filters | DAX measure |
| Stable attribute used in every query | Column in the gold table |
Common pitfalls
- Trying to run INSERT or UPDATE through a lakehouse SQL analytics endpoint.
- Using a snowflake schema in the gold layer without a reason.
- Declaring no grain, so facts mix levels (order header and order line) and totals double count.
- Natural keys in dimensions when history must be tracked.
- Believing a standard view stores data or improves performance by itself.
- Using views as sources for Direct Lake and not noticing DirectQuery fallback.
- Summing precomputed ratios when the correct result needs the ratio of totals in the current filter context.
Exam tip: read verbs closely. "Parameter" suggests a function, "modify or load" suggests a stored procedure, "reuse without storing" suggests a view, and "read-only endpoint" rules out write operations.
Mini case study
Litware Hardware has a bronze lakehouse with raw orders, order lines, customers and products from three regional systems. The finance team knows T-SQL, not Spark. Requirements: a trusted star schema, history of customer region changes, no direct access to the email column for analysts, and a refresh every night.
Proposed solution.
- Build silver tables in the lakehouse with Dataflows Gen2 or a notebook (see how to clean and conform source data in Fabric).
- Create a warehouse for gold. Reach silver tables with cross-database queries or shortcuts.
- Model
FactSalesat order-line grain,DimCustomer(SCD type 2),DimProduct(flattened category hierarchy) andDimDate. - Write
usp_LoadDimCustomerandusp_LoadFactSalesand call them from a pipeline after the silver load. - Create
vw_CustomerPublicwithout the email column; grant SELECT on the view only. - Offer
fn_SalesByRegionfor parameterized analysis. To explore the gold tables, learn how to query a lakehouse with T-SQL and the Visual Query Editor.
Commentary. The warehouse is chosen because the team writes T-SQL and needs DML; view permissions expose a curated subset of columns. Type 2 keys preserve history, and the flattened product dimension keeps the model easy to filter.
Key terms
- View: stored query, no data.
- Inline table-valued function: parameterised view-like query.
- Stored procedure: parameterised T-SQL batch that can modify data.
- CTAS: create a table from a query result.
- Star schema: facts surrounded by dimensions.
- Grain: what one fact row represents.
- Surrogate key: artificial dimension key.
- SCD type 2: history kept as new rows.
- Denormalization: flattening to reduce joins.
- Medallion architecture: bronze, silver, gold layers.
Summary checklist
- I know which objects a lakehouse endpoint and a warehouse can create and which can modify data.
- I can pick between a view, a function and a stored procedure.
- I can design a star schema with a declared grain, surrogate keys and a date dimension.
- I can explain SCD types 1, 2 and 3.
- I can decide when to denormalize and when to avoid it.
- I can say where enrichment belongs: data layer or DAX measure.
Official sources
- Study guide for Exam DP-600: https://learn.microsoft.com/en-us/credentials/certifications/resources/study-guides/dp-600 (opens in a new tab)
- Data warehousing in Microsoft Fabric: https://learn.microsoft.com/en-us/fabric/data-warehouse/data-warehousing (opens in a new tab)
- Tables in a Fabric warehouse (dimensional modelling): https://learn.microsoft.com/en-us/fabric/data-warehouse/dimensional-modeling-overview (opens in a new tab)
- Lakehouse SQL analytics endpoint: https://learn.microsoft.com/en-us/fabric/data-engineering/lakehouse-sql-analytics-endpoint (opens in a new tab)
- Dimensional loads: https://learn.microsoft.com/en-us/fabric/data-warehouse/dimensional-modeling-load-tables (opens in a new tab)
- Warehouse identity columns: https://learn.microsoft.com/en-us/fabric/data-warehouse/identity (opens in a new tab)
- Warehouse transactions: https://learn.microsoft.com/en-us/fabric/data-warehouse/transactions (opens in a new tab)
- Fabric T-SQL surface area: https://learn.microsoft.com/en-us/fabric/data-warehouse/tsql-surface-area (opens in a new tab)
