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, ultimately, 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) By using the CREATE TABLE statement where you explicitly define the components of the table. (2) By using the SELECT INTO 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 and 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 (a namespace) that you can use to group tables and other database objects. A database schema also allows many tables with the same table name to belong to different schemas. This works because the database schema becomes part of the table’s name and helps identify the table. You should always reference objects by using a two-part name (w/ both schema and table 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. Also, there are an additional set of database schemas that are 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

Every database schema must be owned by exactly one authorized database user. That database schema owner can then grant permissions to other users regarding objects in the schema. One user can own many different 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; Moves the Production.Categories table to the Sales database schema. 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 the length restrictions on SQL Server identifiers?

A

Identifiers must be one character long and no longer than 128 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

Regular and Delimited. Regular identifiers are names that follow a set of rules and don’t need to be surrounded by delimiters like square brackets ([]) or quotes (‘’). 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

A regular identifier must have as the first character a letter in the range A-Z (upper or lower), _, @, or #. Variables must begin with an at (@) sign and temporary tables or procedures must begin with a number sign (#). Subsequent characters can include letters, numbers, @, $, #, _. The identifier must not be a reserved keyword in SQL. The identifier must not have spaces.

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

Using quotes as delimiters is the ANSI SQL standard. However, use of quotes requires SET QUOTED_IDENTIFIER is set to ON which is the SQL Server default. Because it’s possible to turn that setting to OFF, using quotation marks is risky. In T-SQL, square brackets can always be used for
delimited identifiers.

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 N/VARCHAR vs N/CHAR data types?

A

When you need to store character strings, if they will likely vary in length, use the NVARCHAR or VARCHAR data type rather than the fixed NCHAR or CHAR. If the column value might be updated often, and especially if it is short, using the fixed length can prevent excessive row movement.

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. Instead, 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 but people generally prefer DECIMAL 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

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

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

How can you specify whether a column allows NULLs or not?

A

You simply state NULL or NOT NULL right after the column’s data type. NULL means the column allows NULLs and NOT NULL means it does not allow NULLs. If a value for a column is optional because no value is known at the time the row is inserted, then define the column as NULL.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
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, e.g.

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
32
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). e.g.

CREATE TABLE Production.Categories
(
categoryid INT IDENTITY(1,1) NOT NULL
)

33
Q

What is the sequence object?

A

You can use sequence objects as an optional way to generate unique numeric values in a table.

34
Q

What are computed columns?

A

Table columns can be defined as values that are computed based on expressions. These expressions could be based on the value of other columns in the row or based on T-SQL functions, e.g.

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

Also, you can make the computed column persisted, i.e. SQL will store the computed values with the table’s data and not compute the values on the fly. If persisted, the column cannot make use of any functions that are non-deterministic which means that the expressions cannot reference various dynamic functions like GETDATE() or CURRENT_TIMESTAMP.

35
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 and (2) Page - SQL Server applies row-level compression plus additional compression algorithms that can be performed at the page level.

36
Q

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

A
CREATE TABLE
(
...
)
WITH (DATA_COMPRESSION = ROW/PAGE);

or you can use:

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

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

A

SQL provides the sp_estimate_data_compression_savings stored procedure.

38
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).

39
Q

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

A

You cannot use ALTER TABLE to (1) change a column’s name, (2) add an identity property, (3) remove an identity property.

40
Q

How do you use ALTER TABLE to add a column?

A

ALTER TABLE Production.CategoriesTest

ADD categoryname VARCHAR(15) NOT NULL;

41
Q

What is IDENTITY_INSERT_ON/OFF?

A

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

42
Q

What are the 6 different types of constraints?

A

(1) NULL, (2) CHECK, (3) DEFAULT, (4) PK, (5) FK, (6) UNIQUE

43
Q

What is declarative data integrity?

A

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

44
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.

45
Q

Do constraints require unique names across the database?

A

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

46
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 - most often, a single column. There can only be one primary key per table.

47
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).

48
Q

What is a surrogate key?

A

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

49
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.

50
Q

How do you declare a primary key?

A

You can declare a primary key with CREATE TABLE or ALTER table statements, e.g.

CREATE TABLE Production.Categories
(
   categoryid INT NOT NULL IDENTITY,
   ...
   CONSTRAINT PK_Categories PRIMARY KEY(categoryid)
)

or

ALTER TABLE Production.Categories
ADD CONSTRAINT PK_Categories PRIMARY KEY(categoryid);

51
Q

What are the requirements to create a primary key?

A

To create a primary key on a column, there are 3 requirements:

(1) The 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.

52
Q

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

A

SQL Server enforces the constraint behind the scenes by creating a unique index on that column and using the primary key column as the keys of the index.

53
Q

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

A

SELECT *
FROM sys.key_constraints
WHERE type = ‘PK’

54
Q

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

A

SELECT *
FROM sys.indexes
WHERE object_id=OBJECT_ID(‘Production.Categories’) AND name = ‘PK_Categories’

55
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.

56
Q

How do you declare/drop a unique constraint?

A

ALTER TABLE Production.Categories
ADD CONSTRAINT UC_Categories UNIQUE (categoryname);

ALTER TABLE Production.Products
DROP CONSTRAINT U_Productname;

57
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.

58
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.

59
Q

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

A

Yes.

60
Q

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

A

You can combine no more than 16 columns as the key columns of the index, and there is a maximum combined width of 900 bytes across those columns.

61
Q

How can you list unique constraints in a database?

A

By querying the sys.key_constraints table filtering on a type of ‘UQ’, e.g.

SELECT *
FROM sys.key_constraints
WHERE type=’UQ’;

62
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.

63
Q

What is a foreign key?

A

A fk is a column or combination of columns in one table that serve as a link to look up data in another table. You can use fk constraints to enforce that every entry into the fk column is a valid value in the lookup table.

64
Q

How do you create/drop a foreign key?

A

ALTER TABLE Production.Products WITH CHECK
ADD CONSTRAINT FK_Products_Categories FOREIGN KEY(categoryid) REFERENCES Production.Categories (categoryid)

ALTER TABLE Production.Products DROP CONSTRAINT FK_Products_Categories;

65
Q

How does the ADD CONSTRAINT command work?

A

(1) You always declare the fk on the table for which this key is “foreign”. (2) You can decide whether to allow violations when you create the constraint. Creating a constraint WITH CHECK implies that if there is any data in the table already and if there would be any violations of the constraint, then the ALTER TABLE will fail. (3) Specify the name of the fk constraint (4) After entering the type of constraint, FOREIGN KEY, you then in parenthesis state the column(s) in this table that you are constraining to be validated by a lookup into another table. (5) Then you state what the other table is using REFERENCES along with the columns in parenthesis. The column in the referenced table must be a primary key, unique constraint, or have a unique index.

66
Q

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

A

(1) The columns must have exactly the same data types and collation (if they have string data type), (2) The columns of the referenced table must have a unique index created on them either implicitly with a pk or unique constraint or explicitly. (3) You can also create fk constraints on computed columns.

67
Q

How can you boost performance on fk joins?

A

You can create a nonclustered index on the fk in the referencing table. There is already a unique index on the column in the referenced table, but if the referencing table has a lot of rows, it may help SQL Server to resolve the join faster if it can use an index on the big table.

68
Q

How can you find the foreign keys in the database?

A

SELECT *
FROM sys.foreign_keys
WHERE name=’FK_Products_Categories’

69
Q

What is a check constraint?

A

With a check constraint, you specify some expression so that SQL Server can constrain the valid values. This goes beyond data type validation and adds additional constraints on the ranges or set of allowable values. The expression can reference other columns in the same row of the table and use built in SQL functions.

70
Q

How do you create a check constraint?

A

ALTER TABLE Production.Products WITH CHECK
ADD CONSTRAINT CHK_Products_unitprice
CHECK (unitprice >= 0)

71
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.

72
Q

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

A

(1) If the column allows for NULLs, make sure the expression accounts for potential NULLs, (2) You cannot customize the error message from a check constraint as you can if you implemented the constraint using a trigger, (3) A check constraint cannot reference the previous value of a column in the check constraint expression, e.g. if you wanted to enforce a constraint that unitprice could not be increased by more then 25%. If you need to do that, you must use a trigger.

73
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.

74
Q

What is a default constraint?

A

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

75
Q

When are default constraints useful?

A

When you have a column in a table that does not allow NULL, but you don’t want to prevent an INSERT from succeeding if it does not specify a value for the column.

76
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.

77
Q

Should 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.

78
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’)