Advanced Database Lecture 1 SQL- Data Definition Language(DDL) Darbandikhan Technical Institute Department of Computer Science Ardalan 1 Content • • • • • • What is SQL? What is DDL? Creating a Database Creating a Table Creating a Table with Constraints Alter table 2 What is SQL? • SQL structure query language • SQL is a standard language for accessing and manipulating databases. What Can SQL do? • SQL can execute queries against a database SQL can retrieve data from a database SQL can insert records in a database SQL can update records in a database SQL can delete records from a database SQL can create new databases SQL can create new tables in a database SQL can create stored procedures in a database SQL can create views in a database SQL can set permissions on tables, procedures, and views 3 What is DDL? • Data Definition Language (DDL) is the part of SQL that allows one to set up a database’s schema, that is, to define attributes, domains for those attributes, defines tables, define relationships among those tables and so on. 4 SQL Data Types 5 BOOLEAN • A Boolean variable is one that is either true or false. – In the Employee table in the Department database, regular field is a Boolean. Either one is a regular employee of the Department or one is not. – In some cases, there may be a third choice for a Boolean variable: NULL. 6 CHAR and VARCHAR • CHAR and VARCHAR are character strings • When defining an attribute of the character type, one includes a length – characterID CHAR(6) – fName VARCHAR(30) the CHAR variable must have the specified length, whereas the VARCHAR variable can be up to the specified length. • Nchar and nvarchar both are Unicode variable length can store both non-Unicode and Unicode characters 7 Difference between char, nchar, varchar and nvarchar Char Nchar Varchar Nvarchar Character Data Type Non-Unicode fixed-length Unicode fixedNon-Unicode length can store variable length both nonUnicode and Unicode characters (i.e. Japanese, Korean etc.) Unicode variable length can store both nonUnicode and Unicode characters (i.e. Japanese, Korean etc.) Maximum Length up to 8,000 characters up to 4,000 characters up to 8,000 characters up to 4,000 characters Character Size takes up 1 byte per character takes up 2 bytes per Unicode/NonUnicode character takes up 1 byte per character takes up 2 bytes per Unicode/NonUnicode character Usage use when data length is constant or fixed length columns use only if you need Unicode support such as the Japanese used when data length is variable or variable length columns and if actual data is always way less than capacity use only if you need Unicode support such as the Japanese 8 INTEGER and SMALLINT • Used for whole numbers, such as: 56, 0 or –77 • There is not always a distinction between INTEGER and SMALLINT, but if there is SMALLINT is used if the numbers are fairly small and one wants to save space. – rooms SMALLINT – population INTEGER 9 NUMERIC and DECIMAL • Used for numbers that have an exact fractional part. • They have a PRECISION (total number of digits) and a SCALE (number of digits after the decimal place). – The number 1234.56789 has a PRECISION of 9 and a SCALE of 5. • The implementation will have a default PRECISION and SCALE to use if they are not specified. – Salary DECIMAL(7,2) 10 NUMERICAL vs DECIMAL • NUMERICAL is stricter on the limits of possible numbers. • For example, with PRESICION 9 and SCALE 5, – the largest NUMERICAL value is strictly 9999.99999 – The largest DECIMAL value may be larger if the implementation can handle it 11 FLOATS, REALS, etc. • In floating point numbers (like scientific notation 6.022 1023), the decimal place moves and digits on the right-hand side (least significant) might be dropped during various calculations. • This allows for a larger range of numbers, but the numbers are handled somewhat more approximately. 12 Decimal VS Floating number • The main difference is Floats and Doubles are binary floating point types and a Decimal will store the value as a floating decimal point type. • Decimals have much higher precision and are usually used within monetary (financial) applications that require a high degree of accuracy. • In performance wise Decimals are slower than double and float types. 13 DATE and TIME • Used for variables that track when something happened. • DATE keeps track of year, month and day. • TIME keeps track of hours, minutes and seconds. 14 Establishing Domains for Attributes • The type tells the computer how to interpret data. • The type also puts restrictions on the values the data is allowed to have. • Further restrictions can be placed on the data by introducing a domain constraint. • A domain is an allowed set of values. 15 NULL or NOT NULL • A simple but important domain constraint is whether or not a value is allowed to be NULL. • NULL is used if the data is unknown or not applicable. • NULL is distinct from 0 for numbers and “” (the empty string) for characters. • The SQL key words are NULL and NOT NULL – NULL means the data can have the NULL value – NOT NULL means it cannot 16 NULL is the default • If nothing is said, NULL is implied. • For example, in the Character table in the Department database – lName VARCHAR(30) – lName VARCHAR(30) NULL would be the same and say that a character may not have a last name – characterID CHAR(6) NOT NULL says that a character must have an ID. 17 Constraints- Value Constraints Value Constraints: – Allows value inserted in the column to be checked condition in the column constraint. • Check clause is used to create a constraint in SQL • Example: CREATE TABLE Movies (movie_title varchar(40) PRIMARY KEY, studio_id Number, budget Number check (budget > 50000) ) • Table level constraints can also be defined using the Constraint keyword • Example: CREATE TABLE Movies (movie_title varchar(40) PRIMARY KEY, studio_id Number, budget Number check (budget > 50000), release_date Date, CONSTRAINT release_date_constraint Check (release_date between ’01-Jan-1980’ and ’31-dec1989)) • Such constraints can be activated and deactivated as required. 18 Constraints- Default Value Default Value: – • A default value can be inserted in any column by using the Default keyword. Example: CREATE TABLE Movies ( movie_title varchar(40) NOT NULL, release_date date DEFAULT sysdate genre varchar(20) DEFAULT ‘Comedy’ In (‘Comedy’, ‘Horror’, ‘Drama’) ) NULL, Check genere • Table level constraints can also be defined using the Constraint keyword • release_date defaults to the current date, however Null value is enabled in the column which will need to be added explicitly when data is added. Note: Any valid expression can be used while specifying constraints • 19 PRIMARY KEY • • • A primary key, also called a primary keyword, is a key in a relational database that is unique for each record. A primary key can not be NULL and that the primary key must uniquely identify a record (known as Entity Integrity). The keyword PRIMARY KEY specifies that attribute(s) will serve this purpose. PRIMARY KEY(characterID) PRIMARY KEY(episodeID, characterID) 20 Candidate Keys • A candidate key is a combination of attributes that can be uniquely used to identify a database record without referring to any other data. Each table may have one or more candidate. One of these candidate keys is selected as the table primary key. • A table contains only one primary key, but it can contain several candidate keys. If a candidate key is composed of two or more columns, then it's called a composite key • A candidate key is an attribute or set of attributes having the same features as the primary key (uniqueness). • To specify that a set of attributes must have this uniqueness property, use the keyword UNIQUE PRIMARY KEY(date, time, room) UNIQUE(date, time, tutee) UNIQUE(date, time, tutor) 21 Foreign Keys • A FOREIGN KEY is a key used to link two tables together. • A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table. • The table containing the foreign key is called the child table, and the table containing the candidate key is called the referenced or parent table. • A foreign key is an attribute in a table that is either NULL or must match a value from another table (called Referential Integrity). • It realizes a relationship between two tables. • The SQL is FOREIGN KEY (personID) REFERENCES RealPerson 22 Referential integrity (RI) • Referential integrity (RI) is a relational database concept, which states that table relationships must always be consistent. • primary key field changes must be applied to all foreign keys, or not at all. The same restriction also applies to foreign keys in that any updates (but not necessarily deletions) must be propagated to the primary parent key. 23 What happens to old relationships? • A foreign key takes it values from another table (its parent in the relationship). What happens if the parent value is updated or deleted? • How will referential integrity be maintained? 24 Four choices for maintaining referential integrity • CASCADE: make same update to child as made to parent • SET NULL: set the child value to NULL when the parent is updated • SET DEFAULT: set the child value to its DEFAULT when the parent is updated • NO ACTION: prevent parent from being updated if children are affected 25 ON DELETE / ON UPDATE • Different choices can be specified depending on what is happening to parent FOREIGN KEY (stateSymbol) REFERENCES State ON DELETE NO ACTION FOREIGN KEY (stateSymbol) REFERENCES State ON UPDATE CASCADE 26 Main DDL statements • SQL allows one to create, alter and destroy domains, tables, views and schemas. • The main SQL DDL statements are: CREATE SCHEMA, DROP SCHEMA CREATE DOMAIN, ALTER DOMAIN, DROP DOMAIN CREATE TABLE, ALTER TABLE, DROP TABLE CREATE VIEW, DROP VIEW 27 CREATE TABLE TableName {(colName dataType [NOT NULL] [UNIQUE] [DEFAULT defaultOption] Define fields [CHECK searchCondition] [,...]} Identify primary key [PRIMARY KEY (listOfColumns),] {[UNIQUE (listOfColumns),] […,]} Identify candidate keys {[FOREIGN KEY (listOfFKColumns) Identify foreign REFERENCES ParentTableName keys, relationships [(listOfCKColumns)], and actions to [ON UPDATE referentialAction] maintain [ON DELETE referentialAction ]] [,…]} referential integrity. {[CHECK (searchCondition)] [,…] }) Business rules 28 CREATE TABLE PropertyForRent ( propertyNo Pnumber NOT NULL, …. rooms Prooms NOT NULL DEFAULT 4, rent Prent NOT NULL, DEFAULT 600, ownerNo OwnerNumber NOT NULL, staffNo StaffNumber Constraint StaffNotHandlingTooMuch …. branchNo BranchNumber NOT NULL, PRIMARY KEY (propertyNo), FOREIGN KEY (staffNo) REFERENCES Staff ON DELETE SET NULL ON UPDATE CASCADE ….); 29 Modifying Records Alter Statement • Alter Statement: – used to make changes to the schema of the table. Columns can be added and the data type of the columns changed as long as the data in those columns conforms to the data type specified. • ALTER TABLE can – – – – Add a new column Remove an existing column Add a new constraint Remove an existing constraint 30 ALTERing Columns To add or remove columns use ALTER TABLE <table> ADD COLUMN <col> ALTER TABLE <table> DROP COLUMN <name> Examples ALTER TABLE Student ADD COLUMN Degree VARCHAR(50) ALTER TABLE Student DROP COLUMN Degree 31 ALTERing Constraints To add or remove columns use ALTER TABLE <table> ADD CONSTRAINT <definition> ALTER TABLE <table> DROP CONSTRAINT <name> Examples ALTER TABLE Module ADD CONSTRAINT ck UNIQUE (title) ALTER TABLE Module DROP CONSTRAINT ck 32 Deleting Tables • To delete a table use • DROP TABLE • [IF EXISTS] • <name> • Example: • DROP TABLE Module • BE CAREFUL with any SQL statement with DROP in it – You will delete any information in the table as well – You won’t normally be asked to confirm – There is no easy way to undo the changes 33