Chapter 8 Creating Tables and Enforcing Data Integrity Flashcards

1
Q

What is the main method used for storing data?

A

Tables (Base tables).

When you query a database for data, that data is located in tables.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do tables work with the SQL Server backup/restore process?

A

When you back up a database, all its tables are backed up, and when you restore the database, all those tables are restored with the same data they had when the backup occurred.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the system tables?

A

They store system data for SQL Server in specially reserved tables called system tables.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is a temporary table?

A

Tables that exist in tempdb and last only as long as a session or scope referencing them endures.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are table variables?

A

Variables that can store table data but only for the duration of a T-SQL batch.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are views?

A

Views appear just like tables but they do not store any data. The are derived from queries against tables.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are indexed views?

A

Indexed views store data but are defined as views and are updated whenever the base tables are updated.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are derived tables and table expressions?

A

Subqueries that are referenced like tables in queries.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are the two ways to create a table in T-SQL?

A
  1. CREATE TABLE: A statement where you explicitly define the components of the table.
  2. SELECT INTO: A statement which creates a table automatically by using the output of a query for the basic table definition.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What options are allowed in the CREATE TABLE statement?

A
  1. Schema name
  2. Table name
  3. Table columns
    1. For each column: data type, data type length/precision, special types of columns (computed, IDENTITY), collation
  4. Constraints,
  5. Storage options (file group, partition schema, table compression).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is a database schema?

A

A database schema is a named container, or namespace,

It is used to group tables and objects.

A database schema allows tables with the same name to belong to the same database.

The database schema is part of the table’s name and helps identify the table.

It is a best practice to use both Schema and Table/Object Name.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What happens if you create a table without specifying the database schema?

A

SQL Server will fill in the database schema with your user name’s default schema.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are four built in database schemas that cannot be dropped?

A
  1. dbo - The default database schema for new objects created by users having db_owner or db_ddl_admin roles.
  2. guest - The schema used to contain objects that would be available to the guest user - rarely used.
  3. INFORMATION_SCHEMA - This schema is used by the Information Schema views which provide ANSI standard access to metadata,
  4. sys - The sys schema is reserved by SQL Server for system objects such as system tables and views.
  5. There are additional database schemas named after the built-in database roles.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Can you create schemas that aren’t linked to users?

A

Yes.

Starting with SQL 2005, you can create schemas that have no intrinsic relationship to users and can serve to give a finer-grained permissions structure to the tables of a database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Can a database schema contain another database schema?

A

No.

There can only be one level of database schema; one schema cannot contain another.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How many users can own a database schema?

A

A database schema is (and must be) owned by exactly one authorized database user.

The database schema owner grants permissions to other users for objects in the schema.

One user can own many database schemas.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How do you create a database schema and define who owns it?

A

CREATE SCHEMA Production AUTHORIZATION [dbo];

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How can you move a table from one schema to another?

A

ALTER SCHEMA Sales TRANSFER Production.Categories;

This moves the table, Production.Categories, into the Sales schema.

It becomes Sales.Categories.

To move it back, use:

ALTER SCHEMA Production TRANSFER Sales.Categories;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What are SQL Server identifiers?

What are the length restrictions on SQL Server identifiers?

A
  1. The database object name is referred to as its identifier. Everything in Microsoft SQL Server can have an identifier. Servers, databases, and database objects, such as tables, views, columns, indexes, triggers, procedures, constraints, and rules, can have identifiers. Identifiers are required for most objects, but are optional for some objects such as constraints.
  2. Both regular and delimited identifiers must contain from 1 through 128 characters. For local temporary tables, the identifier can have a maximum of 116 characters.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What are the two types of SQL Server identifiers?

A
  1. Regular
    1. Regular identifiers are names that follow a set of rules and don’t need to be surrounded by delimiters like square brackets ([]) or quotes (‘’).
  2. Delimited
    1. Delimited identifiers are names that do not adhere to the rules for regular identifiers. You must use delimiters in order to reference them.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What are the rules for regular identifiers?

A
  1. The first character is a letter in the range A-Z (upper or lower), _, @, or #.
  2. After the first character, characters can include letters, numbers, @, $, #, _.
  3. Must not have spaces.
  4. Must not be a reserved keyword in SQL.
  5. Variables must begin with the at (@) sign
  6. Temporary tables must begin with the number sign (#).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What are the rules for delimited identifiers?

A

There is no restriction on what characters can be embedded in them as long as they are delimited, e.g. [Yesterday’s News].

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What’s the difference between the brackets and quotes delimiters?

A
  1. Quotes are the ANSI SQL standard.
  2. In T-SQL the use of quotes requires SET QUOTED_IDENTIFIER is set to ON
    1. The SQL Server default is SET QUOTED_IDENTIFIER ON;
    2. Since it is possible for the setting to be OFF, using quotation marks is risky.
  3. Square brackets are the T-SQL Standard
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Why is it a best practice to use regular identifiers?

A

If one of your users does not use the delimiters in a query, their query will still succeed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

When should you use NVARCHAR vs NCHAR data types?

A

For character strings that vary in length use the NVARCHAR or VARCHAR data type

For character strings that are frequenntly updated or short use NCHAR or CHAR.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

When should you use DATETIME vs DATETIME2 data types?

A

The DATE, TIME, and DATETIME2 data types can store data more efficiently and with better precision than DATETIME and SMALLDATETIME.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

When should you use TEXT, NTEXT, and IMAGE data types?

A

Never.

They are deprecated.

Use the VARCHAR(MAX), NVARCHAR(MAX), and VARBINARY(MAX).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

When should you use DECIMAL/NUMERIC vs FLOAT/REAL?

A

DECIMAL and NUMERIC are the same data type. DECIMAL is prefered because the name is a bit more descriptive.

Use DECIMAL/NUMERIC instead of FLOAT/REAL data types unless you really need floating-point precision and are familiar with the error and possible rounding issues.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

When should you use ROWVERSION vs TIMESTAMP?

A

Never use TIMESTAMP. It is deprecated.

Use ROWVERSION to version-stamp table rows. It is just an incrementing number and does not preserve a date or time.

ROWVERSION is a data type that exposes an automatically generated, unique binary number within a database. The storage size is 8 bytes. The rowversion data type is just an incrementing number and does not preserve a date or a time.

Each database has a counter that is incremented for each insert or update operation that is performed on a table that contains a rowversion column within the database. This counter is the database rowversion. This tracks a relative time within a database, not an actual time that can be associated with a clock. A table can have only one rowversion column. Every time that a row with a rowversion column is modified or inserted, the incremented database rowversion value is inserted in the rowversion column. This property makes a rowversion column a poor candidate for keys, especially primary keys. Any update made to the row changes the rowversion value and, therefore, changes the key value. If the column is in a primary key, the old key value is no longer valid, and foreign keys referencing the old value are no longer valid.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What should you use if you don’t want to allow NULL in the column but you do want to specify some default value to indicate the column has not been populated?

A

Use a DEFAULT constraint by adding the DEFAULT clause right after saying NOT NULL,

CREATE TABLE Production.Categories

(

description VARCHAR(200) NOT NULL DEFAULT (‘’)

)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What does the IDENTITY property on a column do?

A

The IDENTITY property can be assigned to a column in order to automatically generate a sequence of numbers. You can use it for only one column of a table and you can specify both seed (value to begin with) and increment (amount to increment each new number by) values for the number sequence generated. The most common pair is (1,1).

CREATE TABLE Production.Categories

(

categoryid INT IDENTITY(1,1) NOT NULL

)

32
Q

What is the sequence object?

A

Sequence objects are similar to the IDENTITY column. Unlike the IDENTITY column, they are independent and are not attached to any table. Sequence objects are used both independently and within the DML statements i.e. INSERT, UPDATE and DELETE.

Syntax
CREATE SEQUENCE [schema].[Name_of_Sequence]
[AS <data>]<br></br> [START WITH <value>]<br></br> [INCREMENT BY <value>]<br></br> [MINVALUE <value> | NO MINVALUE]<br></br> [MAXVALUE <value> | NO MAXVALUE]<br></br> [CYCLE | NO CYCLE]<br></br> [CACHE value | NO CACHE];<br></br>The syntax works as follows:</value></value></value></value></data>

  1. CREATE SEQUENCE
    1. Used to create a sequence followed by a database schema and the name of the sequence
  2. AS <bigint> Specifies the data type of the sequence.
    </bigint><ol>
    <li>Data types can be Decimal, Int, SmallInt, TinyInt, and BigInt. </li>
    <li>The default value for the data type is BigInt</li>
    </ol></bigint>
  3. START WITH
    1. Sets the starting value for the sequence object
  4. INCREMENT BY
    1. Sets the amount that you want your sequence object to increment by
  5. MIN VALUE
    1. This is an optional parameter that specifies the minimum value for the sequence object
  6. MAX VALUE
    1. This is an optional parameter that sets the maximum value for the sequence object
  7. CYCLE
    1. This specifies if the sequence object should be restarted once it has reached its maximum or minimum value.
    2. It is an optional parameter for which the default value is NO CYCLE
  8. CACHE
    1. This is used to cache sequence object values.
    2. It is also optional parameter with the default value of NO CACHE

A Simple Example
CREATE SEQUENCE [dbo].[NewCounter7]
AS INT
START WITH 10
INCREMENT BY 10
MINVALUE 10
MAXVALUE 50
CYCLE

33
Q

What are computed columns?

A

Table columns defined as values computed from expressions. The expressions can be based on other columns in the table’s row or based on T-SQL functions.

CREATE TABLE Sales.OrderDetails ( initialcost AS unitprice * qty )

The computed column can be persisted, where the value is stored instead of calculated on the fly.

Persisted Calculated Columns must be deterministic.

Non-Deterministic Functions, such as, GETDATE() or CURRENT_TIMESTAMP cannot be used.

34
Q

What are the two levels of table compression available?

A
  1. Row - SQL Server applies a more compact storage format to each row of a table
  2. Page - SQL Server applies row-level compression plus additional compression algorithms that can be performed at the page level.
35
Q

How do you add row/page level compression to a table?

A

CREATE TABLE ( … )

WITH (DATA_COMPRESSION = ROW/PAGE);

Or…

ALTER TABLE Sales.OrderDetails REBUILD WITH (DATA_COMPRESSION = PAGE);

36
Q

How can you determine whether a table with data in it would benefit from compression?

A

Use the

sp_estimate_data_compression_savings

stored procedure.

37
Q

What parts of a table definition can be changed with the ALTER TABLE statement?

A
  1. Add and/or remove columns (new columns are placed at the end of the table’s column order)
  2. Change properties of a column (data type, nullability, constraints).
38
Q

What parts of a table definition cannot be changed with the ALTER TABLE statement?

A
  1. Cannot change a column’s name
    1. –Renaming Column
      EXEC sp_rename‘Schema.Table.Column’,‘NewName’,‘COLUMN’;
      GO
  2. Cannot add an identity property
  3. Cannot remove an identity property.
39
Q

How do you use ALTER TABLE to add a column?

A

ALTER TABLE Production.CategoriesTest ADD categoryname VARCHAR(15) NOT NULL;

40
Q

What is IDENTITY_INSERT Schema.Table ON/OFF?

A

Allows a row to be inserted with an explicit identity value via INSERT statement.

41
Q

What are the 6 different types of constraints?

A
  1. NULL
  2. CHECK
  3. DEFAULT
  4. PRIMARY KEY
  5. FOREIGN KEY
  6. UNIQUE KEY
42
Q

What is declarative data integrity?

A

When you embed methods of data validation inside the definition of the table itself.

43
Q

What is the best way to enforce data integrity in tables?

A

Creating or declaring constraints. You apply these constraints to a table and its columns using the CREATE TABLE/ALTER TABLE statements.

44
Q

Do constraints require unique names across the database?

A

Yes.

All table constraints are database objects, therefore, they must have unique names.

45
Q

What is a primary key?

A

A primary key supplies a unique value for each row and provides a method of distinguishing each row from all the others. It could be one or more columns.

There can only be one primary key per table.

46
Q

What is a natural/business key?

A

A column or combination of columns within the domain of the table’s data that uniquely identifies every row (e.g. categoryname in Production.Categories).

47
Q

What is a surrogate key?

A

A special column with numeric data type (INT) which will have a unique but otherwise meaningless value.

48
Q

Is a natural/business key more appropriate than a surrogate key?

A

It’s more common to use the surrogate key as the primary key and validate the natural key’s uniqueness using a unique constraint.

49
Q

How do you declare a primary key?

A

CREATE TABLE or ALTER table statements, e.g.

CREATE TABLE Production.Categories

(

categoryid INT NOT NULL IDENTITY,

CONSTRAINT PK_Categories PRIMARY KEY(categoryid)

)

ALTER TABLE Production.Categories

ADD CONSTRAINT PK_Categories

PRIMARY KEY(categoryid);

50
Q

What are the requirements to create a primary key?

A

There are 3 requirements:

  1. No column cannot allow NULL
  2. Any data already in the table must have unique values in the primary key column.
  3. There can only be one primary key constraint in a table at a time.
51
Q

What happens behind the scenes when you create a primary key?

A

SQL Server enforces a constraint behind the scenes by creating a unique index on the primary key column(s) and then uses the primary key column(s) as the key of the index.

52
Q

How can you list the primary key constraints in a database?

A

SELECT *

FROM sys.key_constraints

WHERE type = ‘PK’

53
Q

How can you find the unique index that SQL Server uses to enforce a primary key constraint?

A

SELECT *

FROM sys.indexes AS IX

WHERE

IX.OBJECT_ID = OBJECT_ID(‘Production.Categories’)

AND

IX.name = ‘PK_Categories’

54
Q

What is a unique constraint?

A

A unique constraint is very similar to a primary key constraint but are better for validating uniqueness on natural keys.

55
Q

How do you declare/drop a unique constraint?

A

ALTER TABLE Production.Categories

ADD CONSTRAINT UC_Categories

UNIQUE (categoryname);

Or…

ALTER TABLE Production.Products

DROP CONSTRAINT U_Productname;

56
Q

What happens behind the scenes when you create a unique constraint?

A

SQL Server automatically creates a unique index with the same name as the constraint. By default, the index will be non-clustered. SQL Server uses that index to enforce the uniqueness of the column.

57
Q

Does a unique constraint require the column to be NOT NULL?

A

No.

You can allow NULL in a column and still have a unique constraint, but only one row can be NULL.

58
Q

Can you create a PK/Unique Constraint on a computed column?

A

Yes.

The column must be deterministic.

59
Q

What are the size limitations of a PK/Unique Constraint as an index?

A
  1. A maximum 16 columns
  2. The 16 columns’ data cannot exceed 900 bytes across all columns.
60
Q

How can you list unique constraints in a database?

A

SELECT *

FROM sys.key_constraints

WHERE type=’UQ’;

61
Q

How does SQL Server enforce uniqueness in both primary key and unique constraints?

A

SQL Server uses unique indexes to enforce uniqueness for both primary key and unique constraints.

62
Q

What is a foreign key?

A

A column or set of columns in a table that are a link to look up data in another table.

Use fk constraints to enforce data entry into the fk column. This ensures the data is a valid value from the lookup table.

63
Q

How do you create/drop a foreign key?

A
  1. CREATE:

ALTER TABLE Production.Products

WITH CHECK ADD CONSTRAINT FK_Products_Categories

FOREIGN KEY(categoryid)

REFERENCES Production.Categories (categoryid)

  1. DROP:

ALTER TABLE Production.Products

DROP CONSTRAINT FK_Products_Categories;

64
Q

How does the ADD CONSTRAINT command work?

ALTER TABLE Production.Products

WITH CHECK ADD CONSTRAINT FK_Products_Categories

FOREIGN KEY(categoryid)

REFERENCES Production.Categories (categoryid)

A
  1. A FK is declared on the table where the key is foreign
  2. WITH CHECK throws an error if any existing table data violates the constraint
  3. Name the FK constraint
  4. Enter the type of constraint, FOREIGN KEY
    1. then state, in parenthesis, the column(s) names to be validated by a lookup into another table.
  5. State the other table using REFERENCES and the columns in parenthesis.
    1. The column in the Referenced Table must be a
      1. Primary Key,
      2. Unique Constraint,
      3. or have a Unique Index.
65
Q

What rules should you keep in mind when creating foreign keys?

A
  1. The columns must be exactly the same data types and collation.
  2. The Reference Table columns must be in a Primary Key, Unique Key, or Unique Index.

Foreign Key Constraints can be on computed columns

66
Q

How can you boost performance on fk joins?

A

Create a nonclustered index on the key columns in the Foreign Key Table (also called the Referencing Table). Useful only if the table is large.

The Referenced Table is already indexed.

67
Q

How can you find the foreign keys in the database?

A

SELECT *

FROM sys.foreign_keys

WHERE name = ‘FK_Products_Categories’

68
Q

What is a check constraint?

A

A Check Constraint specifies an expression used to constrain a column’s valid values. This is an additional constraint on the ranges or set of allowable values. The expression can reference other columns in the same row of the table, as well as, use built in SQL functions.

ALTER TABLE dbo.Table1 –> Table

ADD ColumnD int NULL –> Add Column

CONSTRAINT CHK_ColumnD –> Constraint Name

CHECK (ColumnD > 10 AND ColumnD < 50); –>Constraint Expression

GO

– Adding values that will pass the check constraint

INSERT INTO dbo.DocExc (ColumnD)

VALUES (49);

GO

– Adding values that will fail the check constraint

INSERT INTO dbo.DocExc (ColumnD)

VALUES (55);

GO

69
Q

How do you create a check constraint?

A

ALTER TABLE Production.Products

WITH CHECK ADD CONSTRAINT CHK_Products_unitprice

CHECK (unitprice >= 0);

70
Q

What are some of the advantages of using check constraints?

A
  1. Their expressions are similar to the filter expressions in a WHERE clause of a SELECT statement.
  2. The constraint is in the table, so it is always enforced, as long as WITH CHECK is specified.
  3. They can perform better than the alternative methods of constraining columns such as triggers.
71
Q

What are some things to watch out for when using check constraints?

A
  1. For columns allowing NULLs, the expression must account for NULLs
  2. A Check Constraint cannot customize the error message for violations, whereas, a trigger can customize error messaging.
  3. A Check Constraint cannot reference another row’s value. To do that, a trigger must be used.
72
Q

How do you list the check constraints for a table?

A

SELECT *

FROM sys.check_constraints

WHERE parent_object_id = OBJECT_ID(‘Production.Products’);

The parent_object_id is the object_id of the table to which the check constraint belongs.

73
Q

What is a default constraint?

A

A default constraint supplies a default value during an INSERT if no other value is supplied.

74
Q

When are default constraints useful?

A

When a column does Not allows NULLs, a default constraint allows an insert to succeed by assigning a value in the table’s DDL.

When a table’s column does not allow NULL, and you want a NULL INSERT to succeed.

75
Q

How do you create a default constraint?

A

CREATE TABLE Production.Products

(

unitprice MONEY NOT NULL CONSTRAINT DEF_Products_unitprice DEFAULT(0)

)

The default constraint is listed right after the column’s data type.

Alternatively, an ALTER TABLE statement could be used to create the constraint.

76
Q

Should a default constraints have unique names?

A

Yes.

They are database wide objects.

Their names must be unique across the entire database.

No two tables can have default constraints named the same.

77
Q

How do you list the default constraints for a table?

A

SELECT *

FROM sys.default_constraints

WHERE parent_object_id = OBJECT_ID(‘Production.Products’);