What is the main method used for storing data?
Tables (Base tables). When you query a database for data, ultimately, that data is located in tables.
How do tables work with the SQL Server backup/restore process?
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.
What are the system tables?
They store system data for SQL Server in specially reserved tables called system tables.
What is a temporary table?
Tables that exist in tempdb and last only as long as a session or scope referencing them endures.
What are table variables?
Variables that can store table data but only for the duration of a T-SQL batch.
What are views?
Views appear just like tables but they do not store any data. The are derived from queries against tables.
What are indexed views?
Indexed views store data but are defined as views and are updated whenever the base tables are updated.
What are derived tables and table expressions?
Subqueries that are referenced like tables in queries.
What are the two ways to create a table in T-SQL?
(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.
What options are allowed in the CREATE TABLE statement?
(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).
What is a database schema?
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).
What happens if you create a table without specifying the database schema?
SQL Server will fill in the database schema with your user name’s default schema.
What are four built in database schemas that cannot be dropped?
(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.
Can you create schemas that aren’t linked to users?
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.
Can a database schema contain another database schema?
No. There can only be one level of database schema; one schema cannot contain another.
How many users can own a database schema?
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 do you create a database schema and define who owns it?
CREATE SCHEMA Production AUTHORIZATION dbo;
How can you move a table from one schema to another?
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;
What are the length restrictions on SQL Server identifiers?
Identifiers must be one character long and no longer than 128 characters.
What are the two types of SQL Server identifiers?
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.
What are the rules for regular identifiers?
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.
What are the rules for delimited identifiers?
There is no restriction on what characters can be embedded in them as long as they are delimited, e.g. [Yesterday’s News].
What’s the difference between the brackets and quotes delimiters?
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
Why is it a best practice to use regular identifiers?
If one of your users does not use the delimiters in a query, their query will still succeed.
When should you use N/VARCHAR vs N/CHAR data types?
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.
When should you use DATETIME vs DATETIME2 data types?
The DATE, TIME, and DATETIME2 data types can store data more efficiently and with better precision than DATETIME and SMALLDATETIME.
When should you use TEXT, NTEXT, and IMAGE data types?
Never. They are deprecated. Instead, use the VARCHAR(MAX), NVARCHAR(MAX), and VARBINARY(MAX).
When should you use DECIMAL/NUMERIC vs FLOAT/REAL?
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.
When should you use ROWVERSION vs TIMESTAMP?
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 can you specify whether a column allows NULLs or not?
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.
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?
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 (‘’)
What does the IDENTITY property on a column do?
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
What is the sequence object?
You can use sequence objects as an optional way to generate unique numeric values in a table.
What are computed columns?
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.
What are the two levels of table compression available?
(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.
How do you add row/page level compression to a table?
CREATE TABLE ( ... ) WITH (DATA_COMPRESSION = ROW/PAGE);
or you can use:
ALTER TABLE Sales.OrderDetails REBUILD WITH (DATA_COMPRESSION = PAGE);
How can you determine whether a table with data in it would benefit from compression?
SQL provides the sp_estimate_data_compression_savings stored procedure.
What parts of a table definition can be changed with the ALTER TABLE statement?
(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).
What parts of a table definition cannot be changed with the ALTER TABLE statement?
You cannot use ALTER TABLE to (1) change a column’s name, (2) add an identity property, (3) remove an identity property.
How do you use ALTER TABLE to add a column?
ALTER TABLE Production.CategoriesTest
ADD categoryname VARCHAR(15) NOT NULL;
What is IDENTITY_INSERT_ON/OFF?
Allows a row to be inserted with an explicit identity value via INSERT statement.
What are the 6 different types of constraints?
(1) NULL, (2) CHECK, (3) DEFAULT, (4) PK, (5) FK, (6) UNIQUE
What is declarative data integrity?
When you embed methods of data validation inside the definition of the table itself.
What is the best way to enforce data integrity in tables?
Creating or declaring constraints. You apply these constraints to a table and its columns using the CREATE TABLE/ALTER TABLE statements.
Do constraints require unique names across the database?
Yes. All table constraints are database objects, therefore, they must have unique names.
What is a primary key?
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.
What is a natural/business key?
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).
What is a surrogate key?
A special column with numeric data type (INT) which will have a unique but otherwise meaningless value.
Is a natural/business key more appropriate than a surrogate key?
It’s more common to use the surrogate key as the primary key and validate the natural key’s uniqueness using a unique constraint.
How do you declare a primary key?
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) )
ALTER TABLE Production.Categories
ADD CONSTRAINT PK_Categories PRIMARY KEY(categoryid);
What are the requirements to create a primary key?
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.
What happens behind the scenes when you create a primary key?
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.
How can you list the primary key constraints in a database?
WHERE type = ‘PK’
How can you find the unique index that SQL Server uses to enforce a primary key constraint?
WHERE object_id=OBJECT_ID(‘Production.Categories’) AND name = ‘PK_Categories’
What is a unique constraint?
A unique constraint is very similar to a primary key constraint but are better for validating uniqueness on natural keys.
How do you declare/drop a unique constraint?
ALTER TABLE Production.Categories
ADD CONSTRAINT UC_Categories UNIQUE (categoryname);
ALTER TABLE Production.Products
DROP CONSTRAINT U_Productname;
What happens behind the scenes when you create a unique constraint?
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.
Does a unique constraint require the column to be NOT NULL?
No. You can allow NULL in a column and still have a unique constraint, but only one row can be NULL.
Can you create a PK/Unique Constraint on a computed column?
What are the size limitations of a PK/Unique Constraint as an index?
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.
How can you list unique constraints in a database?
By querying the sys.key_constraints table filtering on a type of ‘UQ’, e.g.
How does SQL Server enforce uniqueness in both primary key and unique constraints?
SQL Server uses unique indexes to enforce uniqueness for both primary key and unique constraints.
What is a foreign key?
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.
How do you create/drop a foreign key?
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;
How does the ADD CONSTRAINT command work?
(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.
What rules should you keep in mind when creating foreign keys?
(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.
How can you boost performance on fk joins?
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.
How can you find the foreign keys in the database?
What is a check constraint?
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.
How do you create a check constraint?
ALTER TABLE Production.Products WITH CHECK
ADD CONSTRAINT CHK_Products_unitprice
CHECK (unitprice >= 0)
What are some of the advantages of using check constraints?
(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.
What are some things to watch out for when using check constraints?
(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.
How do you list the check constraints for a table?
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.
What is a default constraint?
A default constraint supplies a default value during an INSERT if no other value is supplied.
When are default constraints useful?
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.
How do you create a default constraint?
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.
Should default constraints have unique names?
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.
How do you list the default constraints for a table?