Presentation is loading. Please wait.

Presentation is loading. Please wait.

Managing Tables, Data Integrity, Constraints by Adrienne Watt

Similar presentations


Presentation on theme: "Managing Tables, Data Integrity, Constraints by Adrienne Watt"— Presentation transcript:

1 Managing Tables, Data Integrity, Constraints by Adrienne Watt
5/22/2018 SQL Data Definition Managing Tables, Data Integrity, Constraints by Adrienne Watt

2 5/22/2018 Entering commands The first step in creating queries (DML or DDL) in SQL Server is to open a new query window.

3 5/22/2018 Choosing the Database Once you are ready to enter your command (create table), make sure you are in the correct database. Use the dropdown to select the database.

4 5/22/2018 Entering the Command Enter your create table statement. This table will be created in the Adrienne database.

5 5/22/2018 Datatypes Before you can continue with creating tables, and constraints, you need to know about datatypes. Describes type of data allowed System-supplied datatype Integers Bit - Integer data with either a 1 or 0 value. Int - Integer (whole number) data from -2^31 (-2,147,483,648) through 2^ (2,147,483,647). Smallint - Integer data from 2^15 (-32,768) through 2^ (32,767). Tinyint - Integer data from 0 through 255.

6 5/22/2018 Numeric Datatypes Decimal - Fixed precision and scale numeric data from -10^38 -1 through 10^38 -1. Numeric - A synonym for decimal. Timestamp - A database-wide unique number. Uniqueidentifier - A globally unique identifier (GUID). Money Monetary data values from -2^63 (-922,337,203,685, ) through 2^ (+922,337,203,685, ), with accuracy to a ten- thousandth of a monetary unit. smallmoney Monetary data values from -214, through +214, , with accuracy to a ten-thousandth of a monetary unit.

7 More Datatypes Approximate Numbers
5/22/2018 More Datatypes Approximate Numbers Float - Floating precision number data from -1.79E through 1.79E Real - Floating precision number data from -3.40E + 38 through 3.40E Date and Times datetime Date and time data from January 1, 1753, to December 31, 9999, with an accuracy of three-hundredths of a second, or 3.33 milliseconds. smalldatetime Date and time data from January 1, 1900, through June 6, 2079, with an accuracy of one minute.

8 More Datatypes Character Strings
5/22/2018 More Datatypes Character Strings Char - Fixed-length non-Unicode character data with a maximum length of 8,000 characters. Varchar - Variable-length non-Unicode data with a maximum of 8,000 characters. Text - Variable-length non-Unicode data with a maximum length of 2^ (2,147,483,647) characters. Binary - Fixed-length binary data with a maximum length of 8,000 bytes. Varbinary - Variable-length binary data with a maximum length of 8,000 bytes. Image - Variable-length binary data with a maximum length of 2^ (2,147,483,647) bytes.

9 Managing Tables used for storage and manipulation of data
5/22/2018 Managing Tables used for storage and manipulation of data contain column, which describe data, rows table names must follow the rules for naming identifiers must be unique

10 Create and Modify tables
5/22/2018 Create and Modify tables Column Name Unique within the table Datatype must be a system datatype or user-defined datatype Size Null Default value appears in new record only

11 CREATE TABLE Statement
5/22/2018 CREATE TABLE Statement CREATE TABLE [database.[owner].]table_name ( col_name, column_properties ) table_name col_name column_properties Click on New Query Enter the following statement into the query screen

12 CREATE TABLE Statement
5/22/2018 CREATE TABLE Statement USE HOTEL GO i.e. CREATE TABLE tblHotel (HotelNo Int NOT NULL, Name Char(50) NOT NULL, Address Char(50) NULL, City Char(25) NULL ) Press CTRL-E

13 Data Integrity preserves data consistency in a database
5/22/2018 Data Integrity preserves data consistency in a database All integrity rules should be stored in the database. SQL Server supports declarative referential integrity that enforces data integrity automatically as data is inserted, updated, or deleted from a database. Data integrity falls into four categories: entity integrity, domain integrity, referential integrity, and user-defined integrity.

14 5/22/2018 Identity Property When a new row is added to the table, SQL Server provides a unique, incremental value for that column. Identity columns are often used with the PRIMARY KEY constraints to serve as the unique row identifier for the table. The IDENTITY property can be assigned to a column with a tinyint, smallint, int, decimal, or numeric data type. generates sequential numbers does not enforce entity integrity only one column can have the IDENTITY property must be defined as an integer, numeric or decimal datatype cannot update a column with IDENTITY property cannot contain Null values cannot bind defaults and default constraints to the column

15 Creating an Identity Column
5/22/2018 Creating an Identity Column used with the CREATE TABLE statement IDENTITY[(seed, increment)] seed – is the initial value of the identity column increment – is the value to add to the last increment column i.e. CREATE TABLE tblHotel (HotelNo Int IDENTITY (1,1), Name Char(50) NOT NULL, Address Char(50) NULL, City Char(25) NULL, ) GO

16 5/22/2018 Constraints Constraints are defined to provide data integrity on a table and individual columns in a table. Constraints limit the possible values a user can enter into a table or a column Constraints are added to a table with Enterprise Manager or typed in query analyzer.

17 Primary Key constraint
5/22/2018 Primary Key constraint A table can have only one Primary key. The columns that participate in a Primary key may not accept nulls. Primary keys may consist of as many as 16 columns. Primary key constraints cannot be disabled. [CONSTRAINT constraint_name] PRIMARY KEY [CLUSTERED | NONCLUSTERED] (col_name [, col_name2 […, col_name16]])

18 Primary Key Example USE HOTEL97 GO CREATE TABLE tblHotel (
5/22/2018 Primary Key Example USE HOTEL97 GO CREATE TABLE tblHotel ( HotelNo Int IDENTITY PRIMARY KEY, Name Char(50) NOT NULL UNIQUE, Address Char(50) NULL, City Char(25) NULL, ) Composite Primary Key CONSTRAINT claim_key PRIMARY KEY (policy_no, date_reported))

19 5/22/2018 UNIQUE Constraint Prevents duplicate values from being entered into a column. Both PK and UNIQUE constraints are used to enforce entity integrity. Multiple UNIQUE constraints can be defined for a table. When a UNIQUE constraint is added to an existing table, the existing data is always validated. Can be placed on columns that accept nulls. Only one row can be NULL. Automatically creates a unique index on the selected column. UNIQUE Constraint Syntax: [CONSTRAINT constraint_name] UNIQUE [CLUSTERED | NONCLUSTERED] (col_name [, col_name2 […, col_name16]]) [ON segment_name]

20 ALTER TABLE Constraint
5/22/2018 ALTER TABLE Constraint You can use CREATE TABLE and ALTER TABLE statements to add and drop constraints. ALTER TABLE statement used to add or drop constraints does allow columns to be removed when constraint is added, all existing data is verified for violations

21 UNIQUE constraint example
5/22/2018 UNIQUE constraint example USE HOTEL97 GO ALTER TABLE tblHotel ADD CONSTRAINT unqName UNIQUE (Name)

22 ALTER TABLE IDENTITY Property
5/22/2018 ALTER TABLE IDENTITY Property Use ALTER TABLE statement to add a column with the IDENTITY property. i.e. ALTER TABLE TableName ADD ColumnName int IDENTITY(seed, increment)

23 FOREIGN KEY Constraint
5/22/2018 FOREIGN KEY Constraint defines a column, or combination of columns, whose values match the primary key (PK) of another table. values in a foreign key (FK) are automatically updated when the PK values in the associated table are updated/changed. FK constraints must reference PK or the UNIQUE constraint of another table. number of columns for FK must be same as PK or UNIQUE constraint. if the WITH NOCHECK option is used, the FK constraint will not validate existing data in a table. no index is created on the columns that participate in a FK constraint. FOREIGN KEY Constraint Syntax: [CONSTRAINT constraint_name] [FOREIGN KEY (col_name [, col_name2 […, col_name16]])] REFERENCES [owner.]ref_table [(ref_col [, ref_col2 […, ref_col16]])]

24 5/22/2018 FOREIGN KEY Example USE HOTEL97 GO CREATE TABLE tblRoom ( HotelNo Int NOT NULL , RoomNo Int NOT NULL, Type Char(50) NULL, Price Money NULL, PRIMARY KEY (HotelNo, RoomNo), FOREIGN KEY (HotelNo) REFERENCES tblHotel )

25 CHECK Constraint Restricts values that can be entered into a table.
5/22/2018 CHECK Constraint Restricts values that can be entered into a table. Can contain search conditions similar to a WHERE clause Can reference columns in the same table. The data validation rule for a CHECK constraint must evaluate to a boolean expression. Can be defined for a column that has a rule bound to it. CHECK Constraint Syntax: [CONSTRAINT constraint_name] CHECK [NOT FOR REPLICATION] (expression)

26 5/22/2018 CHECK Constraint USE HOTEL97 GO CREATE TABLE tblRoom ( HotelNo Int NOT NULL, RoomNo Int NOT NULL, Type Char(50) NULL, Price Money NULL, PRIMARY KEY (HotelNo, RoomNo), FOREIGN KEY (HotelNo) REFERENCES tblHotel CONSTRAINT Valid_Type CHECK (Type IN (‘Single’, ‘Double’, ‘Suite’, ‘Executive’)) )

27 5/22/2018 CHECK Constraint CREATE TABLE SALESREPS (Empl_num Int Not Null CHECK (Empl_num BETWEEN 101 and 199), Name Char (15), Age Int CHECK (Age >= 21), Quota Money CHECK (Quota >= 0.0), Hire_Date DateTime, CONSTRAINT QuotaCap CHECK ((Hire_Date < “ ”) OR (Quota <=300000)) )

28 5/22/2018 DEFAULT Constraint Used to supply a value that is automatically added for a column if the user does not supply one. A column can have only one DEFAULT. Cannot be used on columns with timestamp datatype or identity property. Automatically bound to a column when they are created. DEFAULT Constraint Syntax [CONSTRAINT constraint_name] DEFAULT {constant_expression | niladic-function | NULL} [FOR col_name] USE Hotel ALTER TABLE tblHotel Add CONSTRAINT df_city DEFAULT ‘Vancouver’ FOR City

29 User-defined Datatypes
5/22/2018 User-defined Datatypes always based on system-supplied datatype can enforce data integrity Length Allow nulls Default Rule

30 Create a user-defined datatype
5/22/2018 Create a user-defined datatype Choose Types under Programmability in your database. Right click and choose ‘New’  ‘User-defined datatype’ Or Execute the sp_addtype system stored procedure. In a New Query window type: sp_addtype ssn, 'varchar(11)', 'NOT NULL' This will add a new user defined data type called SSN.

31 5/22/2018 Example CREATE TABLE SSNTable ( EmployeeID INT Primary Key, EmployeeSSN SSN, CONSTRAINT CheckSSN CHECK (EmployeeSSN LIKE ‘ [0-9][0-9][0-9] - [0-9][0-9] - [0-9][0-9][0-9][0-9] ‘) )

32 Dropping a Table DROP TABLE [database.]owner.]table_name
5/22/2018 Dropping a Table DROP TABLE [database.]owner.]table_name Make sure you have the correct database selected Enter the following statement into a query Window DROP TABLE tblHotel Press CTRL+E


Download ppt "Managing Tables, Data Integrity, Constraints by Adrienne Watt"

Similar presentations


Ads by Google