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

Slides:



Advertisements
Similar presentations
9 Creating and Managing Tables. Objectives After completing this lesson, you should be able to do the following: Describe the main database objects Create.
Advertisements

Virtual training week 4 structured query language (SQL)
Copyright  Oracle Corporation, All rights reserved. 10 Creating and Managing Tables.
Day 3 - Basics of MySQL What is MySQL What is MySQL How to make basic tables How to make basic tables Simple MySQL commands. Simple MySQL commands.
9 Copyright © Oracle Corporation, All rights reserved. Creating and Managing Tables.
Introduction to Structured Query Language (SQL)
SQL components In Oracle. SQL in Oracle SQL is made up of 4 components: –DDL Data Definition Language CREATE, ALTER, DROP, TRUNCATE. Creates / Alters.
Introduction to Structured Query Language (SQL)
Structured Query Language. Brief History Developed in early 1970 for relational data model: –Structured English Query Language (SEQUEL) –Implemented with.
DATABASES AND SQL. Introduction Relation: Relation means table(data is arranged in rows and columns) Domain : A domain is a pool of values appearing in.
Oracle Data Definition Language (DDL)
Structured Query Language S Q L. What is SQL It is a database programming language developed by IBM in the early 1970’s. It is used for managing and retrieving.
Introduction to DBMS and SQL Introduction to DBMS and SQL GUIDED BY : MR. YOGESH SAROJ (PGT-CS) MR. YOGESH SAROJ (PGT-CS) Presented By : JAYA XII –COM.
Chapter 9 SQL and RDBMS Part C. SQL Copyright 2005 Radian Publishing Co.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
Structured Query Language. Brief History Developed in early 1970 for relational data model: –Structured English Query Language (SEQUEL) –Implemented with.
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Chapter 7 SQL HUANG XUEHUA. SQL SQL server2005 introduction Install components  management studio.
CSC 2720 Building Web Applications Database and SQL.
Oracle Data Definition Language (DDL) Dr. Bernard Chen Ph.D. University of Central Arkansas Fall 2008.
10 Copyright © 2009, Oracle. All rights reserved. Using DDL Statements to Create and Manage Tables.
1 Copyright © 2006, Oracle. All rights reserved. Using DDL Statements to Create and Manage Tables.
Copyright © 2004, Oracle. All rights reserved. Using DDL Statements to Create and Manage Tables.
SQL (DDL & DML Commands)
SQL SQL Server : Overview SQL : Overview Types of SQL Database : Creation Tables : Creation & Manipulation Data : Creation & Manipulation Data : Retrieving.
Chapter 5: Part 1: DDL STRUCTURED QUERY LANGUAGE (SQL)
ACTION QUERIES (SQL COMMANDS ) STRUCTURED QUERY LANGUAGE.
1 Information Retrieval and Use (IRU) CE An Introduction To SQL Part 1.
SQL FUNDAMENTALS SQL ( Structured Query Language )
10 Creating and Managing Tables Objectives At the end of this lesson, you will be able to: Describe the main database objects Create tables Describe.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Oracle 11g DATABASE DEVELOPMENT LAB1. Introduction  Oracle 11g Database:-  Oracle 11g database is designed for some features, which helps to the organizations.
9 Copyright © Oracle Corporation, All rights reserved. Creating and Managing Tables.
Copyright  Oracle Corporation, All rights reserved. 10 Creating and Managing Tables.
Topic 1: Introduction to SQL. SQL stands for Structured Query Language. SQL is a standard computer language for accessing and manipulating databases SQL.
Session 2: SQL (A): Parts 1 and 2 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram.
SQL Fundamentals  SQL: Structured Query Language is a simple and powerful language used to create, access, and manipulate data and structure in the database.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
Tables and Constraints Oracle PL/SQL. Datatypes The SQL Data Definition Language Commands (or DDL) enable us to create, modify and remove database data.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
Prince Sultan University Dept. of Computer & Information Sciences CS 340 Introduction to Database Systems.
SQL: Part 1 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial.
INCLUDING CONSTRAINTS lecture5. Outlines  What are Constraints ?  Constraint Guidelines  Defining Constraint  NOT NULL constraint  Unique constraint.
9 Copyright © Oracle Corporation, All rights reserved. Creating and Managing Tables.
Sql DDL queries CS 260 Database Systems.
Week 8-9 SQL-1. SQL Components: DDL, DCL, & DML SQL is a very large and powerful language, but every type of SQL statement falls within one of three main.
ITS232 Introduction To Database Management Systems Siti Nurbaya Ismail Faculty of Computer Science & Mathematics, Universiti Teknologi MARA (UiTM), Kedah.
Altering Tables and Constraints Database Systems Objectives Add and modify columns. Add, enable, disable, or remove constraints. Drop a table. Remove.
1 CS 430 Database Theory Winter 2005 Lecture 11: SQL DDL.
Creating and Managing Tables 14. ObjectivesObjectives After completing this lesson, you should be able to do the following: After completing this lesson,
Relational Database Management System(RDBMS) Structured Query Language(SQL)
Including Constraints. What Are Constraints? Constraints enforce rules at the table level. You can use constraints to do the following: – Enforce rules.
Introduction to Database SEM I, AY Department of Information Technology Salalah College of Technology Chapter No.3 SQL.
CSCI N311: Oracle Database Programming 5-1 Chapter 15: Changing Data: insert, update, delete Insert Rollback Commit Update Delete Insert Statement –Allows.
SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.
Installation Oracle 11g Express 2 double click the "setup" button to install the Oracle.
LECTURE TWO Introduction to Databases: Data models Relational database concepts Introduction to DDL & DML.
Physical Model Lecture 11. Physical Data Model The last step is the physical design phase, In this phase data is – Store – Organized and – Access.
SQL Statements SELECT INSERTUPDATEDELETECREATEALTERDROPRENAMETRUNCATECOMMITROLLBACKSAVEPOINTGRANTREVOKE Data Retrieval Language (DRL) Data Retrieval Language.
Fundamentals of DBMS Notes-1.
Managing Tables, Data Integrity, Constraints by Adrienne Watt
Manipulating Data.
Manipulating Data Schedule: Timing Topic 40 minutes Lecture
ORACLE SQL Developer & SQLPLUS Statements
STRUCTURED QUERY LANGUAGE
Manipulating Data.
Oracle Data Definition Language (DDL)
SQL-1 Week 8-9.
Session - 6 Sequence - 1 SQL: The Structured Query Language:
IST 318 Database Administration
Presentation transcript:

LECTURE FOUR Introduction to SQL DDL with tables DML with tables

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

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

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

SQL ISO SQL Data Types 4.5

DDL WITH TABLES.

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

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 to and if unsigned, the range is 0 to N.B. INT and INTEGER are Synonymous

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.

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:

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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 Note: A foreign key is preceded by an asterisk (*); Mgr references EmpNo. 4.30

DML WITH TABLES.

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.

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’);

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