Session 2 - Creating, querying data Flashcards
What is the syntax for adding a column to the end of a table?
ALTER TABLE tableName
ADD columnName;
What is the syntax for updating the column type?
ALTER TABLE tableName
ALTER COLUMN columnName datatype
What is the DELETE Syntax?
DELETE
FROM
WHERE
Syntax for adding Unique constraint to column
Alter table MyTable
ADD CONSTRAINT nameOfConstraint UNIQUE (columns)
Syntax for adding a Default Constraint to a new table
columnName dataType (not) null CONSTRAINT constraintName DEFAULT defaultValue
Syntax for adding a Default constraint to an existing column
ALTER TABLE tblName
ADD CONSTRAINT constraintName DEFAULT defaultValue FOR columnName
Syntax for adding a check constraint but to not check the previous rows to verify that they validate the check
ALTER TABLE myTable WITH NOCHECK
ADD CONSTRAINT myConstraint CHECK (col1 = ‘test’)
What is an identity?
Used with PRIMARY KEY and will automatically set a number value. IDENTITY(startingValue, incrementValue)
What is a Primary Key?
Identifying value of a table. It will cluster (order) the table based on this value.
Not Nullable
One Per table
–Surrogate keys are typically numbers that have nothing to do with real life
–Natural Key (Such as Email Address) are naturally keys
Syntax for creating Primary Key
CREATE TABLE tableName (
employeeNumber int CONSTRAINT constraintName PRIMARY KEY IDENTITY(startingValue, incrementValue)
)
Difference between DELETE TABLE and TRUNCATE TABLE regarding Primary Key IDENTITY
DELETING all records allows IDENTITY to keep the next value and TRUNCATE TABLE starts the Identity over
Syntax for adding Primary Key to existing column
ALTER TABLE tableName
ADD CONSTRAINT constraintName PRIMARY KEY (columnName)
You can add NONCLUSTERED if you don’t want it to be clustered (ordered)
ALTER TABLE tableName
ADD CONSTRAINT constraintName PRIMARY KEY NONCLUSTERED (columnName)
What are the effects that you can set when changing a primary key that has foreign keys attached?
NO ACTION
CASCADE
SET NULL
SET DEFAULT
what is NO ACTION for Primary Key change?
Nothing will change in the foreign keys referencing the primary key. Raises error
what is CASCADE for Primary Key change?
Changes will reflect on the foreign keys columns