[1] Create Tables, Enforcing Integrity Flashcards
Give 5 variations of the standard Table.
- Temp tables: a tables that exist only in tempdb and last as long as a session or scope referencing it.
- Table variables: tables that store data only for a batch.
- Views: a query on a table or multiple tables.
- Indexed views: views that update when the base table is updated.
- Derived tables: CTEs. Sub-queries referenced like tables.
What is a database schema and what is it’s primary purpose?
A database schema is a namespace that groups tables together.
What are the 4 built-in database schema and what do they store?
- dbo: default schema for saving new objects for owners/admin users.
- guest schema: stores info for a guest user
INFORMATION_SCHEMA: provides ANSI access to metadata. - system database schema: for system objects like tables/views
What is the syntax to move a table from one schema to another?
ALTER SCHEMA schemaTo TRANSFER schemaCurrent.table
What are the two types of identifiers and how do they differ?
Regular: names that do not require delimiters
Delimited: names that require [] or “”
What does the SET QUOTED_IDENTIFIER setting do?
When ON, it allows for quotations to be used for delimited identifiers
What are the 4 types of constraints when creating/altering a table?
- DEFAULT
- UNIQUE
- PRIMARY KEY
- FOREIGN KEY
- CHECK
Syntax a primary key on column “ID”
CONSTRAINT PK_tablename PRIMARY KEY(ID)
What are the 3 main requirements for creating a primary key out of a column?
- Column must not allow nulls
- Column must have no duplicates
- Column is the only primary key in the table
Syntax to check for primary keys on a table
SELECT *
from sys.key_constraints
WERE type = ‘PK’
What is the difference between a primary key and UNIQUE key columns?
A unique key column can take 1 null value. Primary key columns cannot have any nulls
Syntax to add uniqueness to column “ID”
ALTER TABLE schema.tablename
ADD CONSTRAINT UC_tablename UNIQUE (ID)
Syntax to check for unique keys on a table
SELECT *
from sys.key_constraints
WERE type = ‘UQ’
What is the definition of a foreign key?
A (combination of) column(s) in one table that serve as a link to look up data in another (lookup) table.
Syntax to add a foreign key to column “ID”
ALTER TABLE schema.tablename1
ADD CONSTRAINT FK_tablename FOREIGN KEY (ID)
REFERENCES tablename2 (ID)