0% found this document useful (0 votes)
112 views

Create Database Objects

This document discusses how to create and modify database objects in SQL Server including tables, views, constraints, and triggers. It provides information on creating tables and specifying different types of tables. Common tasks for working with tables like creating, deleting, renaming and modifying columns are also summarized.

Uploaded by

Perbz Jay
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
112 views

Create Database Objects

This document discusses how to create and modify database objects in SQL Server including tables, views, constraints, and triggers. It provides information on creating tables and specifying different types of tables. Common tasks for working with tables like creating, deleting, renaming and modifying columns are also summarized.

Uploaded by

Perbz Jay
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Create database objects (2025%)

Create and alter tables using T-SQL syntax (simple statements)

o Create tables without using the built in tools; ALTER; DROP; ALTER
COLUMN; CREATE
Create and alter views (simple statements)

o Create indexed views; create views without using the built in tools;
CREATE, ALTER, DROP
Design views

o Ensure code non regression by keeping consistent signature for


procedure, views and function (interfaces); security implications
Create and modify constraints (simple statements)

o Create constraints on tables; define constraints; unique constraints;


default constraints; primary and foreign key constraints
Create and alter DML triggers

o Inserted and deleted tables; nested triggers; types of triggers; update


functions; handle multiple rows in a session; performance implications
of triggers
Preparation resources
Tables:

Tables are database objects that contain all the data in a database. In tables,
data is logically organized in a row-and-column format similar to a spreadsheet.
Each row represents a unique record, and each column represents a field in the
record. For example, a table that contains employee data for a company might
contain a row for each employee and columns representing employee
information such as employee number, name, address, job title, and home
telephone number.
The number of tables in a database is limited only by the number of objects
allowed in a database (2,147,483,647). A standard user-defined table can
have up to 1,024 columns. The number of rows in the table is limited only by
the storage capacity of the server.
You can assign properties to the table and to each column in the table to
control the data that is allowed and other properties. For example, you can
create constraints on a column to disallow null values or provide a default
value if a value is not specified, or you can assign a key constraint on the
table that enforces uniqueness or defines a relationship between tables.
The data in the table can be compressed either by row or by page. Data
compression can allow more rows to be stored on a page. For more
information, see Data Compression.
Types of Tables
Besides the standard role of basic user-defined tables, SQL Server provides the
following types of tables that serve special purposes in a database.
Partitioned Tables
Partitioned tables are tables whose data is horizontally divided into units which
may be spread across more than one filegroup in a database. Partitioning makes
large tables or indexes more manageable by letting you access or manage
subsets of data quickly and efficiently, while maintaining the integrity of the
overall collection. By default, SQL Server 2016 supports up to 15,000 partitions.
For more information, see Partitioned Tables and Indexes.
Temporary Tables
Temporary tables are stored in tempdb. There are two types of temporary
tables: local and global. They differ from each other in their names, their
visibility, and their availability. Local temporary tables have a single number sign
(#) as the first character of their names; they are visible only to the current
connection for the user, and they are deleted when the user disconnects from
the instance of SQL Server. Global temporary tables have two number signs (##)
as the first characters of their names; they are visible to any user after they are
created, and they are deleted when all users referencing the table disconnect
from the instance of SQL Server.
System Tables
SQL Server stores the data that defines the configuration of the server and all its
tables in a special set of tables known as system tables. Users cannot directly
query or update the system tables. The information in the system tables is made
available through the system views. For more information, see System Views
(Transact-SQL).
Wide Tables:
Wide tables use sparse columns to increase the total of columns that a table can
have to 30,000. Sparse columns are ordinary columns that have an optimized
storage for null values. Sparse columns reduce the space requirements for null
values at the cost of more overhead to retrieve nonnull values. A wide table has
defined a column set, which is an untyped XML representation that combines all
the sparse columns of a table into a structured output. The number of indexes
and statistics is also increased to 1,000 and 30,000, respectively. The maximum
size of a wide table row is 8,019 bytes. Therefore, most of the data in any
particular row should be NULL. The maximum number of nonsparse columns plus
computed columns in a wide table remains 1,024.
Wide tables have the following performance implications.
Wide tables can increase the cost to maintain indexes on the table. We
recommend that the number of indexes on a wide table be limited to the
indexes that are required by the business logic. As the number of indexes
increases, so does the DML compile-time and memory requirement.
Nonclustered indexes should be filtered indexes that are applied to data
subsets. For more information, see Create Filtered Indexes.
Applications can dynamically add and remove columns from wide tables.
When columns are added or removed, compiled query plans are also
invalidated. We recommend that you design an application to match the
projected workload so that schema changes are minimized.
When data is added and removed from a wide table, performance can be
affected. Applications must be designed for the projected workload so that
changes to the table data is minimized.
Limit the execution of DML statements on a wide table that update multiple
rows of a clustering key. These statements can require significant memory
resources to compile and execute.
Switch partition operations on wide tables can be slow and might require
large amounts of memory to process. The performance and memory
requirements are proportional to the total number of columns in both the
source and target partitions.
Update cursors that update specific columns in a wide table should list the
columns explicitly in the FOR UPDATE clause. This will help optimize
performance when you use cursors.
Common Table Tasks
The following table provides links to common tasks associated with creating or
modifying a table.

Table Tasks Topic

Create Tables
Describes how to create a table.
(Database Engine)

Delete Tables
Describes how to delete a table.
(Database Engine)

Describes how to create a new table that contains


Duplicate Tables
some or all of the columns in an existing table.

Rename Tables
Describes how to rename a table.
(Database Engine)

View the Table


Describes how to view the properties of the table.
Definition

Describes how to determine whether other objects such View the


Table Tasks Topic

Dependencies of a
as a view or stored procedure depend on a table.
Table
The following table provides links to common tasks associated with creating or
modifying columns in a table.

Column Tasks Topic

Describes how to add columns to an existing Add Columns to a Table


table. (Database Engine)

Delete Columns from a


Describes how to delete columns from a table.
Table

Rename Columns
Describes how to change the name of a column.
(Database Engine)

Describes how to copy columns from one table to Copy Columns from One
another, copying either just the column definition, Table to Another
or the definition and data. (Database Engine)

Describes how to modify a column definition, by Modify Columns (Database


changing the data type or other property. Engine)

Describes how to change the order in which the Change Column Order in a
columns appear. Table

Describes how to create a computed column in a Specify Computed


table. Columns in a Table

Describes how to specify a default value for a


Specify Default Values for
column. This value is used if another value is not
Columns
supplied.

Views

A view is a virtual table whose contents are defined by a query. Like a table, a
view consists of a set of named columns and rows of data. Unless indexed, a
view does not exist as a stored set of data values in a database. The rows and
columns of data come from tables referenced in the query defining the view and
are produced dynamically when the view is referenced.
A view acts as a filter on the underlying tables referenced in the view. The query
that defines the view can be from one or more tables or from other views in the
current or other databases. Distributed queries can also be used to define views
that use data from multiple heterogeneous sources. This is useful, for example, if
you want to combine similarly structured data from different servers, each of
which stores data for a different region of your organization.
Views are generally used to focus, simplify, and customize the perception each
user has of the database. Views can be used as security mechanisms by letting
users access data through the view, without granting the users permissions to
directly access the underlying base tables of the view. Views can be used to
provide a backward compatible interface to emulate a table that used to exist
but whose schema has changed. Views can also be used when you copy data to
and from SQL Server to improve performance and to partition data.
Types of Views
Besides the standard role of basic user-defined views, SQL Server provides the
following types of views that serve special purposes in a database.

Indexed Views
An indexed view is a view that has been materialized. This means the view
definition has been computed and the resulting data stored just like a table. You
index a view by creating a unique clustered index on it. Indexed views can
dramatically improve the performance of some types of queries. Indexed views
work best for queries that aggregate many rows. They are not well-suited for
underlying data sets that are frequently updated.

Partitioned Views
A partitioned view joins horizontally partitioned data from a set of member
tables across one or more servers. This makes the data appear as if from one
table. A view that joins member tables on the same instance of SQL Server is a
local partitioned view.

System Views
System views expose catalog metadata. You can use system views to return
information about the instance of SQL Server or the objects defined in the
instance. For example, you can query the sys.databases catalog view to return
information about the user-defined databases available in the instance. For more
information, see System Views (Transact-SQL)
Common View Tasks
The following table provides links to common tasks associated with creating or
modifying a view.
View Tasks Topic
Describes how to create a view. Create Views
Describes how to create an indexed view. Create Indexed Views
Describes how to modify the view definition. Modify Views
Describes how to modify data through a view. Modify Data Through a View
Describes how to delete a view. Delete Views
Describes how to return information about a view such as the view definition.
Get Information About a View
Describes how to rename a view. Rename Views
table_constraint (Transact-SQL)

Specifies the properties of a PRIMARY KEY, UNIQUE, FOREIGN KEY, or CHECK


constraint, or a DEFAULT definition added to a table by using ALTER TABLE.

Topic link icon Transact-SQL Syntax Conventions


Syntax

[ CONSTRAINT constraint_name ]
{
{ PRIMARY KEY | UNIQUE }
[ CLUSTERED | NONCLUSTERED ]
(column [ ASC | DESC ] [ ,...n ] )
[ WITH FILLFACTOR = fillfactor
[ WITH ( <index_option>[ , ...n ] ) ]
[ ON { partition_scheme_name ( partition_column_name ... )
| filegroup | "default" } ]
| FOREIGN KEY
( column [ ,...n ] )
REFERENCES referenced_table_name [ ( ref_column [ ,...n ] ) ]
[ ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ]
[ ON UPDATE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ]
[ NOT FOR REPLICATION ]
| DEFAULT constant_expression FOR column [ WITH VALUES ]
| CHECK [ NOT FOR REPLICATION ] ( logical_expression )
}
Arguments

CONSTRAINT: Specifies the start of a definition for a PRIMARY KEY, UNIQUE,


FOREIGN KEY, or CHECK constraint, or a DEFAULT.
constraint_name: Is the name of the constraint. Constraint names must
follow the rules for identifiers, except that the name cannot start with a number
sign (#). If constraint_name is not supplied, a system-generated name is
assigned to the constraint.
PRIMARY KEY

Is a constraint that enforces entity integrity for a specified column or columns


by using a unique index. Only one PRIMARY KEY constraint can be created for
each table.
UNIQUE

Is a constraint that provides entity integrity for a specified column or columns


by using a unique index.
CLUSTERED | NONCLUSTERED

Specifies that a clustered or nonclustered index is created for the PRIMARY


KEY or UNIQUE constraint. PRIMARY KEY constraints default to CLUSTERED.
UNIQUE constraints default to NONCLUSTERED.

If a clustered constraint or index already exists on a table, CLUSTERED cannot


be specified. If a clustered constraint or index already exists on a table, PRIMARY
KEY constraints default to NONCLUSTERED.

Columns that are of the ntext, text, varchar(max), nvarchar(max),


varbinary(max), xml, or image data types cannot be specified as columns for an
index.
column

Is a column or list of columns specified in parentheses that are used in a new


constraint.
[ ASC | DESC ]

Specifies the order in which the column or columns participating in table


constraints are sorted. The default is ASC.
WITH FILLFACTOR =fillfactor

Specifies how full the Database Engine should make each index page used to
store the index data. User-specified fillfactor values can be from 1 through 100. If
a value is not specified, the default is 0.
Important note Important

Documenting WITH FILLFACTOR = fillfactor as the only index option that


applies to PRIMARY KEY or UNIQUE constraints is maintained for backward
compatibility, but will not be documented in this manner in future releases.
Other index options can be specified in the index_option clause of ALTER TABLE.
ON { partition_scheme_name(partition_column_name) | filegroup| "default" }

Specifies the storage location of the index created for the constraint. If
partition_scheme_name is specified, the index is partitioned and the partitions
are mapped to the filegroups that are specified by partition_scheme_name. If
filegroup is specified, the index is created in the named filegroup. If "default" is
specified or if ON is not specified at all, the index is created in the same filegroup
as the table. If ON is specified when a clustered index is added for a PRIMARY
KEY or UNIQUE constraint, the whole table is moved to the specified filegroup
when the clustered index is created.

In this context, default is not a keyword; it is an identifier for the default


filegroup and must be delimited, as in ON "default" or ON [default]. If "default" is
specified, the QUOTED_IDENTIFIER option must be ON for the current session.
This is the default setting.
FOREIGN KEY REFERENCES

Is a constraint that provides referential integrity for the data in the column.
FOREIGN KEY constraints require that each value in the column exist in the
specified column in the referenced table.
referenced_table_name
Is the table referenced by the FOREIGN KEY constraint.
ref_column

Is a column or list of columns in parentheses referenced by the new FOREIGN


KEY constraint.
ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT }

Specifies what action happens to rows in the table that is altered, if those rows
have a referential relationship and the referenced row is deleted from the parent
table. The default is NO ACTION.

NO ACTION

The SQL Server Database Engine raises an error and the delete action on
the row in the parent table is rolled back.
CASCADE

Corresponding rows are deleted from the referencing table if that row is
deleted from the parent table.
SET NULL

All the values that make up the foreign key are set to NULL when the
corresponding row in the parent table is deleted. For this constraint to execute,
the foreign key columns must be nullable.
SET DEFAULT

All the values that comprise the foreign key are set to their default values
when the corresponding row in the parent table is deleted. For this constraint to
execute, all foreign key columns must have default definitions. If a column is
nullable and there is no explicit default value set, NULL becomes the implicit
default value of the column.
Do not specify CASCADE if the table will be included in a merge publication
that uses logical records. For more information about logical records, see Group
Changes to Related Rows with Logical Records.

ON DELETE CASCADE cannot be defined if an INSTEAD OF trigger ON DELETE


already exists on the table that is being altered.

For example, in the AdventureWorks2012 database, the ProductVendor table


has a referential relationship with the Vendor table. The ProductVendor.VendorID
foreign key references the Vendor.VendorID primary key.

If a DELETE statement is executed on a row in the Vendor table and an ON


DELETE CASCADE action is specified for ProductVendor.VendorID, the Database
Engine checks for one or more dependent rows in the ProductVendor table. If any
exist, the dependent rows in the ProductVendor table will be deleted, in addition
to the row referenced in the Vendor table.

Conversely, if NO ACTION is specified, the Database Engine raises an error and


rolls back the delete action on the Vendor row when there is at least one row in
the ProductVendor table that references it.
ON UPDATE { NO ACTION | CASCADE | SET NULL | SET DEFAULT }

Specifies what action happens to rows in the table altered when those rows
have a referential relationship and the referenced row is updated in the parent
table. The default is NO ACTION.

NO ACTION

The Database Engine raises an error, and the update action on the row in
the parent table is rolled back.
CASCADE

Corresponding rows are updated in the referencing table when that row is
updated in the parent table.
SET NULL
All the values that make up the foreign key are set to NULL when the
corresponding row in the parent table is updated. For this constraint to execute,
the foreign key columns must be nullable.
SET DEFAULT

All the values that make up the foreign key are set to their default values
when the corresponding row in the parent table is updated. For this constraint to
execute, all foreign key columns must have default definitions. If a column is
nullable, and there is no explicit default value set, NULL becomes the implicit
default value of the column.

Do not specify CASCADE if the table will be included in a merge publication


that uses logical records. For more information about logical records, see Group
Changes to Related Rows with Logical Records.

ON UPDATE CASCADE, SET NULL, or SET DEFAULT cannot be defined if an


INSTEAD OF trigger ON UPDATE already exists on the table that is being altered.

For example, in the AdventureWorks2012 database, the ProductVendor table


has a referential relationship with the Vendor table. The ProductVendor.VendorID
foreign key references the Vendor.VendorID primary key.

If an UPDATE statement is executed on a row in the Vendor table and an ON


UPDATE CASCADE action is specified for ProductVendor.VendorID, the Database
Engine checks for one or more dependent rows in the ProductVendor table. If any
exist, the dependent row in the ProductVendor table will be updated, as well as
the row referenced in the Vendor table.

Conversely, if NO ACTION is specified, the Database Engine raises an error and


rolls back the update action on the Vendor row when there is at least one row in
the ProductVendor table that references it.
NOT FOR REPLICATION

Can be specified for FOREIGN KEY constraints and CHECK constraints. If this
clause is specified for a constraint, the constraint is not enforced when
replication agents perform insert, update, or delete operations.
DEFAULT

Specifies the default value for the column. DEFAULT definitions can be used to
provide values for a new column in the existing rows of data. DEFAULT definitions
cannot be added to columns that have a timestamp data type, an IDENTITY
property, an existing DEFAULT definition, or a bound default. If the column has an
existing default, the default must be dropped before the new default can be
added. If a default value is specified for a user-defined type column, the type
should support an implicit conversion from constant_expression to the user-
defined type. To maintain compatibility with earlier versions of SQL Server, a
constraint name can be assigned to a DEFAULT.
constant_expression

Is a literal value, a NULL, or a system function that is used as the default


column value. If constant_expression is used in conjunction with a column
defined to be of a Microsoft .NET Framework user-defined type, the
implementation of the type must support an implicit conversion from the
constant_expression to the user-defined type.
FOR column

Specifies the column associated with a table-level DEFAULT definition.


WITH VALUES

Specifies that the value given in DEFAULT constant_expression is stored in a


new column that is added to existing rows. WITH VALUES can be specified only
when DEFAULT is specified in an ADD column clause. If the added column allows
null values and WITH VALUES is specified, the default value is stored in the new
column that is added to existing rows. If WITH VALUES is not specified for
columns that allow nulls, NULL is stored in the new column in existing rows. If
the new column does not allow nulls, the default value is stored in new rows
regardless of whether WITH VALUES is specified.
CHECK

Is a constraint that enforces domain integrity by limiting the possible values


that can be entered into a column or columns.
logical_expression
Is a logical expression used in a CHECK constraint and returns TRUE or FALSE.
logical_expression used with CHECK constraints cannot reference another table
but can reference other columns in the same table for the same row. The
expression cannot reference an alias data type.

Remarks

When FOREIGN KEY or CHECK constraints are added, all existing data is verified
for constraint violations unless the WITH NOCHECK option is specified. If any
violations occur, ALTER TABLE fails and an error is returned. When a new
PRIMARY KEY or UNIQUE constraint is added to an existing column, the data in
the column or columns must be unique. If duplicate values are found, ALTER
TABLE fails. The WITH NOCHECK option has no effect when PRIMARY KEY or
UNIQUE constraints are added.

Each PRIMARY KEY and UNIQUE constraint generates an index. The number of
UNIQUE and PRIMARY KEY constraints cannot cause the number of indexes on
the table to exceed 999 nonclustered indexes and 1 clustered index. Foreign key
constraints do not automatically generate an index. However, foreign key
columns are frequently used in join criteria in queries by matching the column or
columns in the foreign key constraint of one table with the primary or unique key
column or columns in the other table. An index on the foreign key columns
enables the Database Engine to quickly find related data in the foreign key table.
Work with data (2530%)
Query data by using SELECT statements

o Use the ranking function to select top(X) rows for multiple categories in
a single query; write and perform queries efficiently using the new
(SQL 2005/8->) code items such as synonyms, and joins (except,
intersect); implement logic which uses dynamic SQL and system
metadata; write efficient, technically complex SQL queries, including all
types of joins versus the use of derived tables; determine what code
may or may not execute based on the tables provided; given a table
with constraints, determine which statement set would load a table;
use and understand different data access technologies; case versus
isnull versus coalesce
Implement sub-queries

o Identify problematic elements in query plans; pivot and unpivot; apply


operator; cte statement; with statement
Implement data types
o Use appropriate data; understand the uses and limitations of each data
type; impact of GUID (newid, newsequentialid) on database
performance, when to use what data type for columns
Implement aggregate queries

o New analytic functions; grouping sets; spatial aggregates; apply


ranking functions
Query and manage XML data

o Understand XML datatypes and their schemas and interop w/,


limitations and restrictions; implement XML schemas and handling of
XML data; XML data: how to handle it in SQL Server and when and
when not to use it, including XML namespaces; import and export XML;
XML indexing
Preparation resources
SELECT (Transact-SQL)

INTO clause (Transact-SQL)

FROM (Transact-SQL)

Modify data (2025%)


Create and alter stored procedures (simple statements)

o Write a stored procedure to meet a given set of requirements;


branching logic; create stored procedures and other programmatic
objects; techniques for developing stored procedures; different types of
storeproc result; create stored procedure for data access layer;
program stored procedures, triggers, functions with T-SQL
Modify data by using INSERT, UPDATE, and DELETE statements

o Given a set of code with defaults, constraints, and triggers, determine


the output of a set of DDL; know which SQL statements are best to
solve common requirements; use output statement
Combine datasets

o Difference between UNION and UNION all; case versus isnull versus
coalesce; modify data by using MERGE statements
Work with functions

o Understand deterministic, non-deterministic functions; scalar and table


values; apply built-in scalar functions; create and alter user-defined
functions (UDFs)
Preparation resources
CREATE PROCEDURE (Transact-SQL)

ALTER PROCEDURE (Transact-SQL)

INSERT (Transact-SQL)

Troubleshoot and optimize (2530%)


Optimize queries

o Understand statistics; read query plans; plan guides; DMVs; hints;


statistics IO; dynamic vs. parameterized queries; describe the different
join types (HASH, MERGE, LOOP) and describe the scenarios they
would be used in
Manage transactions

o Mark a transaction; understand begin tran, commit, and rollback;


implicit vs explicit transactions; isolation levels; scope and type of
locks; trancount
Evaluate the use of row-based operations vs. set-based operations

o When to use cursors; impact of scalar UDFs; combine multiple DML


operations
Implement error handling

o Implement try/catch/throw; use set based rather than row based logic;
transaction management
Preparation resources
Transaction statements (Transact-SQL)

SET TRANSACTION ISOLATION LEVEL (Transact-SQL)

Cursors

You might also like