Presentation is loading. Please wait.

Presentation is loading. Please wait.

LECTURE FOUR Introduction to SQL DDL with tables DML with tables.

Similar presentations


Presentation on theme: "LECTURE FOUR Introduction to SQL DDL with tables DML with tables."— Presentation transcript:

1 LECTURE FOUR Introduction to SQL DDL with tables DML with tables

2 SQL Introduction to SQL  It is stands for Structured Query Language. It is also known as a transform-oriented language ( a language designed to use relations to transform inputs to outputs ).  A database language must be able to allow a user to create a database and relation structures, perform basic data management tasks and, perform simple and complex queries.  It should be portable (use commands that allows one to move from one DBMS to another easily), have an easy to learn command structure and syntax. 4.2

3 SQL SQL Statements- Summary SELECTData Retrieval CREATE, ALTER, DROP, RENAME, TRUNCATE Data definition Language (DDL)‏ INSERT, UPDATE, DELETE MERGE Data Manipulation Language (DML)‏ COMMIT, ROLLBACK, SAVEPOINT Transaction Control GRANT, REVOKEData Control Language (DCL)‏ 4.3

4 SQL SQL Statements cont’d StatementDescription SELECTRetrieves data from the database CREATE, ALTER, DROP, RENAME, TRUNCATE Sets up, changes and removes data structures from tables INSERT, UPDATE, DELETE MERGE Enters new rows, changes existing rows and removes unwanted rows from tables in a database COMMIT, ROLLBACK, SAVEPOINT Manages changes made by DML. Changes to data may be grouped into logical transactions GRANT, REVOKEGives and removes access rights to both the database and the structures within it. 4.4

5 SQL ISO SQL Data Types 4.5

6 DDL WITH TABLES.

7 SQL MySQL Data Types Properly defining fields is important for overall optimisation of your database. These types of fields are referred to as data types because they represent the type of data you will be storing in those fields. MySQL uses many different data types which are broken into 3 categories i.e. Numeric, Date and Time and string types. N.B. Declaring the correct data type is the most important part of table creation. 4.7

8 SQL Numeric Data Types The terms Signed and Unsigned will be used in the list of numeric data types. Signed refers to a positive or negative number whereas unsigned refers to a non-negative number. Examples of Numeric Data Types include: 1.INT--A normal sized integer that can be signed or unsigned. If signed, the allowable range is -2147483648 to 2147483647 and if unsigned, the range is 0 to 4294967295 N.B. INT and INTEGER are Synonymous

9 SQL Numeric Data Types Integers can further be classified as; TINYINT, SMALLINT, MEDIUMINT AND BIGINT. 2.Float (M,D)--Refers to a floating point number that can not be unsigned. You can define the display length, M and the number of decimals,D. This is however not required and will default to 10,2. 3. Double (M,D)--A double precision floating point number that can not be unsigned. You can define the display length and the number of decimals. This is not required and the default will be 16,4.

10 SQL Data Types Continued 4.Decimal (M,D)--A floating point number that can not be unsigned and each decimal corresponds to one byte. Defining the display length, M and number of decimals, D is required. MySQL has several data types for storing date and Time types and these data types are flexible in their input. These include: DATE, DATETIME, TIME, YEAR(M) which stores a year in a 2 or 4 digit format e.t.c. The commonly used string data types are as follows:

11 SQL Data Types Continued CHAR (M) --A fixed length string between 1 and 255 characters in length, e.g. CHAR (5). Defining a length is not required but the default is 1 2. VARCHAR (M) --A variable length string between 1and 255 characters in length, e.g.VARCHAR (25). You must define a length when creating a VARCHAR field. NB: Read about the various string data types that exist in MySQL like TEXT, TINYTEXT, MEDIUMTEXT, LONGTEXT AND ENUM.

12 SQL Creating a Table  Involves using the CREATE TABLE statement which includes: Specifying a table name [mandatory] Defining columns of the table [mandatory] Column name [mandatory] Column data type [mandatory] Column constraints [optional] Providing a default value [optional] Specifying table constraints [optional] 4.12

13 SQL Creating Table Syntax CREATE TABLE table_name ( column_name data_type [column_constraint] [DEFAULT expr], ….…. [, table_constraints] )‏ Example - considering only mandatory specifications. CREATE TABLE emp (emp_id number, name varchar(30)); 4.13

14 SQL Create Table – using the DEFAULT option  Example: CREATE TABLE students (regNo varchar(15), name varchar(20), dob date, gender char(1) default ‘M’); 4.14

15 SQL Create Table – MySQL Example The Ex. Below creates a generic grocery_inventory table with fields for ID, name, description, price and quantity Mysql> Create table grocery_inventory ( id int not null primary key auto_increment, item_name varchar (50) not null, item_desc text, item_price float not null, curr_qty int not null); Auto_Increment is a table modifier/constraint that will request MySQL to add the next available number to the ID field for you. 4.15

16 Exercise  Write an SQL statement to create the following tables Branch(branchNo, street, city, postcode)‏ Staff(staffNo, fName, lName, position, sex, DOB, salary)‏ SQL4.16

17 SQL Create Table – using table and column constraints  Constraints enforce rules on data whenever a row is inserted, updated, or deleted from a table. The constraints have to be satisfied for the operation to succeed.  Data Integrity Constraints: Not null: specifies that the column cannot contain a null value. Unique: specifies that a column or combination of columns whose values must be unique for all rows in the table. 4.17

18 SQL Create Table – using table and column constraints cont’d Check: specifies a condition that must be true Primary key: uniquely identifies each row of the table Foreign key: establishes and enforces a foreign key relationship between the column and a column of the referenced table.  Constraints can be divided at one of the two levels i. Column constraint: References a single column and is defined within the column definition. Can define any type of integrity constraint. 4.18

19 SQL o Table constraint: References one or more columns and is defined after the column list. Can define any constraint except not null.  It is an issue of style to define constraints at either table level or column level; however, the not null constraint must be strictly defined at the column level. Create Table – using table and column constraints Cont’d 4.19

20 SQL Example:  [using column constraints] create table students (regNo varchar(15) constraint students_regNo_pk primary key, name varchar(20), dob date, gender char(1) constraint students_gender_nn not null); OR [using table constraints] create table students (regNo varchar(15), name varchar(20), dob date, gender char(1) not null, constraint students_regNo_pk primary key(regNo));  How would you confirm constraints defined on a table? Create Table – using table and column constraints Cont’d 4.20

21 SQL Creating Tables Using Subqueries  The table is created with the specified column names, and the rows retrieved by the select statement are inserted into the table.  The column definition can contain only the column name and default value.  If column specifications are given, the number of columns must equal the number of columns in the subquery select list. 4.21

22 SQL Creating Tables Using Subqueries cont’d  If no column specifications are given, the column names of the table are the same as the column names in the subquery.  Only the not null constraint and data types are passed onto the new table.  Be sure to give a column alias when selecting an expression. 4.22

23 SQL Creating a table by using a subquery  [providing column specifications] create table dept20 (empno primary key, ename, ann_sal) as select employee_id, last_name || first_name, salary*12 “annual salary” from employees where department_id =20; OR  [without providing column specifications] create table dept20 as select employee_id, last_name || ‘ ‘ || first_name name, salary*12 “annual salary” from employees where department_id=20; 4.23

24 SQL Modifying a Table Structure  Modifying a table involves using the ALTER TABLE statement which could cater for three kinds of adjustments: MODIFY column (modify [data type/size][not null][default]) ADD column(s) / constraint(s), DROP column(s) / constraint(s)‏  Examples: ALTER TABLE students ADD weight number; alter table students add height number; alter table students MODIFY weight number(4); 4.24

25 SQL Modifying a Table Structure cont’d alter table students drop column height; alter table students modify gender default ‘F’; Alter table students add constraint students_gender_ck check (gender in (‘M’,’F’)); Alter table students add constraint students_name_uk unique (name); alter table students drop constraint students_name_uk; 4.25

26 SQL Notes:  The not null constraint is added by modifying the column that is to be defined as not null Example: ALTER TABLE students MODIFY weight not null;  Adjustments to populated tables is more restrictive because the adjustments should not violet the nature of data stored in the tables. Modifying a Table Structure Cont’d 4.26

27 Exercise 1. Modify the branch table to include the country column. 2. Assuming that Sex has data type char, modify the staff table such that it can accept values of varied lengths. 3. Modify the staff table such that each staff member had a position. SQL

28 Removing a Table from a DB schema  Example: DROP TABLE students; 4.28

29 SQL Quiz  Why does the statement fail to execute: create table dept20 as select employee_id, last_name || ' ' || first_name, salary*12 "annual salary" from employees where department_id=20;  Identify the error in this statement: alter table students add constraint students_name_nn not null; 4.29

30 SQL Quiz Cont’d  Write all SQL statements that will create the relational DB schema: DEPTS (DeptNo, DName, Loc)‏ PERSONNEL (EmpNo, EName, Job, * Mgr, HireDate, Sal, Comm, * DeptNo)‏ Data Constraints: A department name value must never be repeated. No person should earn a salary that is more than 5000. Note: A foreign key is preceded by an asterisk (*); Mgr references EmpNo. 4.30

31 DML WITH TABLES.

32 SQL Using the Insert Command 4.32 After creating some tables, you will use the SQL INSERT Command to add new records to the tables. The general syntax for insert is as follows: INSERT INTO table_name (column list) values (Column values); N.B.1. String “column values” should be enclosed within quotation marks. The SQL standard is single quotes although MySQL also enables the use of double quotes.

33 SQL Using the Insert Command N.B.2. Integers do not require quotation marks around them. N.B.3. Notice that the insert statement contains a column list and value list. However, only the “value list” is actually required. Considering the grocery_inventory table ; Example 1. Insert into grocery_inventory (id, item_name,item_desc, item_price, curr_qty) values (‘2’, ‘Apples’, Beautiful, ripe apples.’, ‘0.25’, ‘1000’);

34 SQL Using the Insert Command Example 2. Insert into grocery_inventory values (‘2’, ‘Apples’, Beautiful, ripe apples.’, ‘0.25’, ‘1000’);


Download ppt "LECTURE FOUR Introduction to SQL DDL with tables DML with tables."

Similar presentations


Ads by Google