Common Database Objects
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 14 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Module: Relational Data on Azure
Section: SQL Statements
Lesson: Common Database Objects
Introduction: The Building Blocks of Relational Data
When we talk about relational database systems like Azure SQL Database or SQL Server, we are essentially talking about organized containers for information. While the data itself is the lifeblood of an application, the structure that holds, processes, and secures that data is defined by what we call "database objects." Understanding these objects is fundamental to working effectively with any relational system. If you think of a database as a digital filing cabinet, database objects are the folders, the labels, the sorting mechanisms, and the automated assistants that help you retrieve exactly what you need, when you need it.
In the Azure cloud environment, managing these objects correctly is even more critical than on-premises. Because you often pay for the resources your database consumes, designing efficient objects—like tables that are properly indexed or views that simplify complex queries—directly impacts your monthly costs and the performance of your applications. This lesson will walk you through the most common database objects you will encounter, explaining what they are, how to implement them, and why they matter in a modern data architecture.
Not read yet
1. Tables: The Foundation of Relational Data
Tables are the most basic and important objects in any relational database. A table is a collection of related data entries consisting of columns and rows. You can think of a table as a grid where each row represents a unique record and each column represents a specific attribute of that record. In SQL, tables are defined by a schema that dictates what type of data can be stored in each column, such as integers, text strings, dates, or boolean values.
Creating a table requires careful planning regarding data types and constraints. If you define a column as a string but only ever store numbers in it, you waste storage and potentially cause performance issues when the database tries to perform mathematical operations.
Example: Creating a Customer Table
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY IDENTITY(1,1),
FirstName NVARCHAR(50) NOT NULL,
LastName NVARCHAR(50) NOT NULL,
Email NVARCHAR(100) UNIQUE,
CreatedAt DATETIME DEFAULT GETDATE()
);
In this example, we define several critical aspects of a table:
- Primary Key: The
CustomerIDacts as the unique identifier for every row. - Identity: The
IDENTITY(1,1)clause tells the database to automatically generate a new number for every new customer, starting at 1 and incrementing by 1. - Constraints:
NOT NULLensures we cannot save a record without a name, andUNIQUEprevents duplicate email addresses.
Callout: Why Schema Design Matters A well-designed table schema is the difference between a fast application and a sluggish one. When you define your columns, always choose the smallest data type that fits your needs. For instance, if a column will only store numbers from 0 to 255, use a
TINYINTinstead of anINT. This reduces the physical footprint of the table on the disk and in memory, leading to faster read and write operations.
Not read yet
2. Views: Virtual Tables for Simplified Access
A view is a virtual table based on the result-set of an SQL statement. It does not store the data itself; rather, it stores the query logic. When you query a view, the database engine executes the underlying SQL statement and returns the results to you as if you were querying a physical table. Views are incredibly powerful because they allow you to hide the complexity of underlying table joins and provide a consistent interface for your applications.
When to use views:
- Security: You can grant a user access to a view that only shows non-sensitive columns, effectively hiding sensitive data like salaries or social security numbers.
- Simplification: If your report requires joining five different tables, you can create a view that performs the join once, so developers don't have to rewrite the complex join logic every time they need that data.
- Consistency: If you change the underlying table structure, you can update the view to match the old structure, preventing your application code from breaking.
CREATE VIEW View_ActiveCustomers AS
SELECT FirstName, LastName, Email
FROM Customers
WHERE CreatedAt > '2023-01-01';
Note: Views are not a performance panacea. Because a view executes the underlying query every time it is called, a poorly written view that joins massive tables will be just as slow as the query itself. Always test your views with realistic data volumes.
Not read yet
3. Indexes: The Secret to Performance
If a table is a book, an index is the index at the back of the book. Without an index, the database engine must perform a "table scan," reading every single row in the table to find the record you requested. With an index, the engine jumps directly to the relevant data, saving massive amounts of processing time.
There are two main types of indexes you should know:
- Clustered Index: This determines the physical order of data in the table. Because a table can only be sorted in one way, you can have only one clustered index per table. By default, the Primary Key is usually the clustered index.
- Non-Clustered Index: This is a separate structure from the data rows. It contains the indexed column values and a pointer to the actual row in the table. You can have many non-clustered indexes on a single table.
Creating a Non-Clustered Index
CREATE INDEX IX_Customers_Email
ON Customers(Email);
This index makes searching for customers by their email address almost instantaneous, regardless of how many millions of rows are in the Customers table.
Not read yet
4. Stored Procedures: Encapsulating Logic
Stored procedures are collections of SQL statements that are grouped together and saved as a single object in the database. They allow you to write complex business logic once and call it multiple times, often with different input parameters. Stored procedures are highly efficient because they are compiled by the database engine, meaning the execution plan is cached and reused.
Example: A Stored Procedure for Adding Customers
CREATE PROCEDURE sp_AddCustomer
@FirstName NVARCHAR(50),
@LastName NVARCHAR(50),
@Email NVARCHAR(100)
AS
BEGIN
INSERT INTO Customers (FirstName, LastName, Email)
VALUES (@FirstName, @LastName, @Email);
END;
This approach is safer than writing raw SQL in your application code because it prevents SQL injection attacks. By using parameters (@FirstName, etc.), you ensure that the input is treated as data rather than executable code.
Not read yet
5. Functions: Reusable Calculations
SQL functions are similar to stored procedures in that they contain reusable logic, but they are designed to return a value. There are two main types:
- Scalar Functions: Return a single value (like a number or a string).
- Table-Valued Functions: Return a table, allowing you to use the function's output in a
FROMclause of another query.
Example: Scalar Function
CREATE FUNCTION fn_GetFullName (@FirstName NVARCHAR(50), @LastName NVARCHAR(50))
RETURNS NVARCHAR(101)
AS
BEGIN
RETURN @FirstName + ' ' + @LastName;
END;
You can then use this function in a select statement:
SELECT dbo.fn_GetFullName(FirstName, LastName) AS FullName FROM Customers;
Warning: Be cautious with scalar functions in
WHEREclauses. If you use a function on a column in aWHEREclause (e.g.,WHERE YEAR(CreatedAt) = 2023), the database engine may be forced to ignore existing indexes, leading to a full table scan. This is a common performance pitfall.
Not read yet
6. Triggers: Automated Responses
Triggers are special types of stored procedures that automatically execute when a specific event occurs in the database, such as an INSERT, UPDATE, or DELETE operation on a table. They are excellent for auditing or maintaining data integrity that is too complex for standard constraints.
Example: An Audit Trigger
CREATE TRIGGER trg_AuditCustomerChange
ON Customers
AFTER UPDATE
AS
BEGIN
PRINT 'A customer record has been updated.';
END;
While powerful, triggers should be used sparingly. Because they run automatically, they can lead to hidden performance issues or unexpected behavior if a developer forgets they exist. Always document your triggers clearly in your database schema documentation.
Comparison of Database Objects
| Object Type | Primary Purpose | Key Characteristic |
|---|---|---|
| Table | Storing raw data | Physical storage; foundation of schema |
| View | Query abstraction | Virtual; does not store data itself |
| Index | Performance optimization | Separate structure; speeds up lookups |
| Stored Procedure | Encapsulating logic | Pre-compiled; accepts parameters |
| Function | Reusable calculations | Returns a value or a result set |
| Trigger | Automation | Event-driven; runs automatically |
Not read yet
Best Practices for Working with Database Objects
When working in Azure, you have the benefit of advanced monitoring tools like Query Store and SQL Insights. However, the best performance comes from good design. Follow these industry-standard practices:
- Naming Conventions: Develop a consistent naming convention and stick to it. For example, prefix stored procedures with
sp_orusp_, views withvw_, and indexes withIX_. This makes managing a database with hundreds of objects much easier. - Schema Separation: Use schemas to group related objects. Instead of putting everything in the default
dboschema, use schemas likeSales,HR, orLogging. This improves security and organization. - Documentation: Comment your code. Explain why a particular index exists or what a complex stored procedure is supposed to achieve. Future developers (or your future self) will thank you.
- *Avoid "Select ": Always explicitly name the columns you need in your queries. This reduces network traffic and prevents your application from breaking if the table schema changes (e.g., a new column is added).
- Test at Scale: A query that runs fast with 100 rows might fail with 1,000,000 rows. Always test your indexes and queries with realistic data volumes before deploying to production.
Not read yet
Common Pitfalls and How to Avoid Them
Even experienced developers fall into traps when working with database objects. Here are the most common mistakes:
- Over-indexing: While indexes speed up reads, they slow down writes because the database must update the index every time a row is inserted or updated. Only index columns that are frequently used in
WHERE,JOIN, orORDER BYclauses. - Neglecting Data Types: Using
NVARCHAR(MAX)for every string column might seem convenient, but it consumes unnecessary memory and can hurt performance. Use specific lengths whenever possible. - Ignoring Transaction Scope: In stored procedures, ensure your transactions are handled correctly. If an error occurs halfway through an update, you want the database to roll back to the original state, not leave it in a half-finished, corrupted state.
- Hardcoding Values: Never hardcode configuration values or business rules directly into your SQL code. Use parameters or configuration tables to make your logic flexible.
- Overusing Triggers: Triggers can make debugging difficult because they execute "behind the scenes." If you find yourself writing complex logic in a trigger, consider moving that logic into the application layer or a stored procedure that is called explicitly.
Not read yet
Implementing Database Objects: Step-by-Step
To get you started, here is a practical workflow for adding a new feature to your database. Suppose your application needs to track "Orders" for our "Customers."
Step 1: Design the Table
First, define the table structure. Ensure you include foreign keys to relate the orders to the customers.
CREATE TABLE Orders (
OrderID INT PRIMARY KEY IDENTITY(1,1),
CustomerID INT NOT NULL,
OrderDate DATETIME DEFAULT GETDATE(),
TotalAmount DECIMAL(18, 2),
CONSTRAINT FK_Orders_Customers FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
Step 2: Add Performance Indexes
Think about how you will query this data. You will likely search by CustomerID often.
CREATE INDEX IX_Orders_CustomerID ON Orders(CustomerID);
Step 3: Create a View for Reporting
Create a view that joins customers and orders so you can see who placed which order.
CREATE VIEW vw_CustomerOrders AS
SELECT c.FirstName, c.LastName, o.OrderID, o.OrderDate, o.TotalAmount
FROM Customers c
JOIN Orders o ON c.CustomerID = o.CustomerID;
Step 4: Create a Stored Procedure for Business Logic
Create a way to insert data safely.
CREATE PROCEDURE sp_CreateOrder
@CustomerID INT,
@TotalAmount DECIMAL(18, 2)
AS
BEGIN
INSERT INTO Orders (CustomerID, TotalAmount)
VALUES (@CustomerID, @TotalAmount);
END;
This workflow ensures that your data is structured, performant, secure, and easy to maintain.
Callout: The Importance of Foreign Keys Foreign keys are more than just a way to link tables; they are a critical tool for maintaining data integrity. By defining a foreign key, you tell the database that an order must be associated with a valid customer. If you try to delete a customer who has orders, the database will block the operation, preventing "orphaned" records that could crash your application. Always use foreign keys when a logical relationship exists.
Not read yet
Advanced Considerations: Azure-Specific Objects
When working in Azure, you have access to specialized objects that aren't present in traditional SQL Server instances. For example, Memory-Optimized Tables are designed for high-throughput transactional processing. By moving a table into memory, you eliminate disk I/O bottlenecks, though you must be careful about memory limits.
Another Azure-specific consideration is External Tables. These allow you to query data stored in Azure Blob Storage or Data Lake as if it were a local table. This is incredibly useful for big data scenarios where you want to keep your primary database small and performant while archiving historical data in cheaper storage.
Example: Creating an External Table (Conceptual)
CREATE EXTERNAL TABLE ext_HistoricalOrders (
OrderID INT,
OrderDate DATETIME,
TotalAmount DECIMAL(18, 2)
)
WITH (
LOCATION = 'orders/2022/',
DATA_SOURCE = my_blob_storage_datasource,
FILE_FORMAT = parquet_file_format
);
These objects show how the relational model is evolving to meet the needs of the modern cloud, where data is often distributed across different storage types and formats.
Not read yet
Managing Change: Schema Versioning
One of the biggest challenges in database management is keeping your database objects in sync with your application code. If your application expects a table to have a PhoneNumber column but your database doesn't have it yet, the application will crash.
The industry standard for solving this is Database Migration Scripts. Instead of manually creating tables in the Azure portal, you write SQL scripts for every change. You then use a tool (like Liquibase, Flyway, or Azure DevOps deployment tasks) to apply these scripts in order.
A typical migration script looks like this:
-- Migration: AddPhoneNumberToCustomers.sql
IF NOT EXISTS (SELECT * FROM sys.columns
WHERE object_id = OBJECT_ID('Customers')
AND name = 'PhoneNumber')
BEGIN
ALTER TABLE Customers ADD PhoneNumber NVARCHAR(20);
END;
By using this pattern, you ensure that your database changes are repeatable, version-controlled, and testable. Never skip this step in a professional environment.
Not read yet
FAQ: Common Questions
Q: Should I use Views or Stored Procedures for reading data? A: Use Views when you want to provide a consistent, simplified look at the data for reporting or general access. Use Stored Procedures when you need to perform complex filtering based on user input, or when you need to perform multiple operations (like checking a balance before inserting a row).
Q: Can I have too many indexes?
A: Yes. Every index adds overhead to INSERT, UPDATE, and DELETE operations. Aim for a balance. Monitor your database usage and remove indexes that are never used.
Q: How do I know if my database object is slow? A: Use the Azure SQL Query Performance Insight tool. It will show you which queries are consuming the most resources and suggest missing indexes that could help.
Q: Is it okay to use SELECT * in a View?
A: Generally, no. Even in a view, it is better to list the specific columns. This makes it clear what the view returns and prevents issues if the underlying table schema changes unexpectedly.
Not read yet
Key Takeaways
As you conclude this lesson, keep these core principles in mind to ensure your database objects are robust and efficient:
- Data Integrity is Paramount: Always use constraints (Primary Keys, Foreign Keys, Unique, Not Null) to ensure your data remains clean and reliable. A database with bad data is useless, regardless of how fast it is.
- Design for Performance: Don't wait until your database is slow to think about performance. Design your tables with appropriate data types and create indexes based on how your application will actually query the data.
- Encapsulation Matters: Use Stored Procedures and Views to hide the complexity of your database. This allows you to change the underlying structure without breaking the applications that rely on it.
- Consistency is Key: Whether it's naming conventions or schema management, consistency reduces errors and makes your system easier to maintain. Use automated migration scripts to manage changes.
- Understand the Tools: Know the difference between a table, a view, and a function. Each has a specific purpose, and using the right tool for the job is the hallmark of a skilled database developer.
- Security by Design: Use views and stored procedures to control access to your data. Don't give application users direct access to raw tables if you can avoid it; instead, provide access through objects that enforce your business rules.
- Monitor and Adapt: A database is a living system. Regularly review your performance metrics in the Azure portal and don't be afraid to drop unused objects or refine existing ones as your application's needs evolve.
By mastering these database objects, you are building the foundation for reliable, scalable, and high-performance applications in the Azure ecosystem. Remember that every object you create serves a specific purpose, and thoughtful design at this stage will save you countless hours of troubleshooting and optimization in the future. Happy coding!
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
- Understanding Structured Data
- Understanding Structured Data Quiz5q
- Features of Structured Data
- Features of Structured Data Quiz5q
- Semi-Structured Data Concepts
- Semi-Structured Data Concepts Quiz5q
- Features of Semi-Structured Data
- Features of Semi-Structured Data Quiz5q
- Understanding Unstructured Data
- Understanding Unstructured Data Quiz5q
- Features of Unstructured Data
- Features of Unstructured Data Quiz5q
- Transactional Workloads Overview
- Transactional Workloads Overview Quiz5q
- Features of Transactional Workloads
- Features of Transactional Workloads Quiz5q
- OLTP Systems
- OLTP Systems Quiz5q
- Analytical Workloads Overview
- Analytical Workloads Overview Quiz5q
- Features of Analytical Workloads
- Features of Analytical Workloads Quiz5q
- OLAP Systems
- OLAP Systems Quiz5q
- SQL Statement Types
- SQL Statement Types Quiz5q
- SELECT Statement Basics
- SELECT Statement Basics Quiz5q
- INSERT UPDATE DELETE Statements
- INSERT UPDATE DELETE Statements Quiz5q
- Common Database Objects
- Common Database Objects Quiz5q
- Views Stored Procedures and Functions
- Views Stored Procedures and Functions Quiz5q
- JOIN Operations
- JOIN Operations Quiz5q
- Azure SQL Family Overview
- Azure SQL Family Overview Quiz5q
- Azure SQL Database
- Azure SQL Database Quiz5q
- Azure SQL Managed Instance
- Azure SQL Managed Instance Quiz5q
- SQL Server on Azure VMs
- SQL Server on Azure VMs Quiz5q
- Azure Database for MySQL
- Azure Database for MySQL Quiz5q
- Azure Database for PostgreSQL
- Azure Database for PostgreSQL Quiz5q
- Azure Database for MariaDB
- Azure Database for MariaDB Quiz5q
- Azure Cosmos DB Overview
- Azure Cosmos DB Overview Quiz5q
- Cosmos DB Use Cases
- Cosmos DB Use Cases Quiz5q
- Cosmos DB APIs Overview
- Cosmos DB APIs Overview Quiz5q
- Cosmos DB for NoSQL
- Cosmos DB for NoSQL Quiz5q
- Cosmos DB for MongoDB
- Cosmos DB for MongoDB Quiz5q
- Cosmos DB for Apache Cassandra
- Cosmos DB for Apache Cassandra Quiz5q
- Cosmos DB for Apache Gremlin
- Cosmos DB for Apache Gremlin Quiz5q
- Cosmos DB for Table
- Cosmos DB for Table Quiz5q
- Global Distribution in Cosmos DB
- Global Distribution in Cosmos DB Quiz5q
- Data Ingestion Concepts
- Data Ingestion Concepts Quiz5q
- Data Processing Considerations
- Data Processing Considerations Quiz5q
- Analytical Data Stores
- Analytical Data Stores Quiz5q
- Data Warehouses and Data Lakes
- Data Warehouses and Data Lakes Quiz5q
- Azure Databricks Overview
- Azure Databricks Overview Quiz5q
- Microsoft Fabric Overview
- Microsoft Fabric Overview Quiz5q
- Azure Synapse Analytics
- Azure Synapse Analytics Quiz5q
- Azure Data Factory
- Azure Data Factory Quiz5q
- Power BI Overview
- Power BI Overview Quiz5q
- Power BI Capabilities
- Power BI Capabilities Quiz5q
- Power BI Data Models
- Power BI Data Models Quiz5q
- Data Model Features
- Data Model Features Quiz5q
- Power BI Visualizations
- Power BI Visualizations Quiz5q
- Choosing Appropriate Visualizations
- Choosing Appropriate Visualizations Quiz5q
- Reports and Dashboards
- Reports and Dashboards Quiz5q
- Power BI Desktop vs Service
- Power BI Desktop vs Service Quiz5q
- Data Refresh and Gateways
- Data Refresh and Gateways Quiz5q
Spend your points to unlock exam-style practice questions
Spend points to unlock DP-900 exam-style practice questions.
Practice for DP-900