Creating SQL Tables and using Data Types

Similar documents
To understand the concept of candidate and primary keys and their application in table creation.

School of Computing, Engineering and Information Sciences University of Northumbria. Set Operations

SQL Structured Query Language Introduction

Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No.

Full file at Chapter 2: An Introduction to SQL

Advanced Handle Definition

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan

INTRODUCTION TO DATABASE

27 Formulas and Variables

An Introduction to Structured Query Language

Creating and Managing Tables Schedule: Timing Topic

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

Databases IIB: DBMS-Implementation Exercise Sheet 13

NULLs & Outer Joins. Objectives of the Lecture :

SELF TEST. List the Capabilities of SQL SELECT Statements

DBLOAD Procedure Reference

Starting with a great calculator... Variables. Comments. Topic 5: Introduction to Programming in Matlab CSSE, UWA

JME Language Reference Manual

DATABASE DEVELOPMENT (H4)

RAQUEL s Relational Operators

Programming the Database

Downloaded from

Slides by: Ms. Shree Jaswal

Full file at

Database Modelling. Lecture 5 Part 1: Updating Database 1/6/2015 1

Illustrative Example of Logical Database Creation

1) Introduction to SQL

C Language, Token, Keywords, Constant, variable

Why Relational Databases? Relational databases allow for the storage and analysis of large amounts of data.

Office Wo Office W r o d r 2007 Revi i ng and R d Refifini ng a D Document

PASS4TEST. IT Certification Guaranteed, The Easy Way! We offer free update service for one year

Illustrative Example of Logical Database Creation

Maciej Sobieraj. Lecture 1

A <column constraint> is a constraint that applies to a single column.

Database Modelling. Lecture 4 (b): Database Integrity, Keys & Constraints. Akhtar Ali 10/14/2014 1

Database Management Systems,

2) SQL includes a data definition language, a data manipulation language, and SQL/Persistent stored modules. Answer: TRUE Diff: 2 Page Ref: 36

You can write a command to retrieve specified columns and all rows from a table, as illustrated

chapter 2 G ETTING I NFORMATION FROM A TABLE

An Introduction to Structured Query Language

Database implementation Further SQL

An Introduction to Structured Query Language

Programming Lecture 3

Test Bank for Database Processing Fundamentals Design and Implementation 13th Edition by Kroenke

A Simple Guide to Using SPSS (Statistical Package for the. Introduction. Steps for Analyzing Data. Social Sciences) for Windows

SQL: Data De ni on. B0B36DBS, BD6B36DBS: Database Systems. h p:// Lecture 3

An Introduction to Structured Query Language

Information Systems Engineering. SQL Structured Query Language DDL Data Definition (sub)language

Illustrative Example of Physical Schema Usage

TUTORIAL FOR IMPORTING OTTAWA FIRE HYDRANT PARKING VIOLATION DATA INTO MYSQL

An Introduction to Structured Query Language

Data about data is database Select correct option: True False Partially True None of the Above

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Variables and Constants

WHAT IS A DATABASE? There are at least six commonly known database types: flat, hierarchical, network, relational, dimensional, and object.

Basant Group of Institution

Mahathma Gandhi University

Arrays. Defining arrays, declaration and initialization of arrays. Designed by Parul Khurana, LIECA.

SQL. Char (30) can store ram, ramji007 or 80- b

GIFT Department of Computing Science Data Selection and Filtering using the SELECT Statement

T-SQL Training: T-SQL for SQL Server for Developers

Test Bank for A Guide to SQL 9th Edition by Pratt

1 SQL Structured Query Language

Getting Information from a Table

Sample Question Paper

set in Options). Returns the cursor to its position prior to the Correct command.

SPEECH RECOGNITION COMMON COMMANDS

1.8 Database and data Data Definition Language (DDL) and Data Manipulation Language (DML)

Creating the Data Layer

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Full file at

Based on the following Table(s), Write down the queries as indicated: 1. Write an SQL query to insert a new row in table Dept with values: 4, Prog, MO

Databases. Relational Model, Algebra and operations. How do we model and manipulate complex data structures inside a computer system? Until

CS2 Current Technologies Note 1 CS2Bh

RDBMS File Access Guide

Chapter 17: Table & Integrity Contraints. Informatics Practices Class XII. By- Rajesh Kumar Mishra. KV No.1, AFS, Suratgarh

Relational Model History. COSC 416 NoSQL Databases. Relational Model (Review) Relation Example. Relational Model Definitions. Relational Integrity

The Relational Model

Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras

Database Management Systems,

)454 : 4(% #(!2!#4%2 3%4!.$ "!3)# %,%-%.43 -!.-!#().%,!.'5!'% )454 Recommendation : INTERNATIONAL TELECOMMUNICATION UNION

Text Processing (Business Professional)

CITS2401 Computer Analysis & Visualisation

1 SQL Structured Query Language

TUTORIAL FOR IMPORTING OTTAWA FIRE HYDRANT PARKING VIOLATION DATA INTO MYSQL

BMC Remedy AR System change ID utility

SQL STRUCTURED QUERY LANGUAGE

Text Processing (Business Professional)

Text Processing (Business Professional)

Formatting the spreadsheet data

Babu Madhav Institute of Information Technology 2015

TEXT PROCESSING (BUSINESS PROFESSIONAL) Mailmerge Level 1 (06971) Credits: 4. Learning Outcomes The learner will 1 Be able to use a word processor

EECS-3421a: Test #1 Design

CSCU9Q5 Introduction to MySQL. Data Definition & Manipulation (Over ~two Lectures)

Text Processing (Business Professional) within the Business Skills suite

COMP 110 Project 1 Programming Project Warm-Up Exercise

A Flat file database. Problems with a flat file database (data redundancy)

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

What is SQL? Toolkit for this guide. Learning SQL Using phpmyadmin

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama

Transcription:

Creating SQL Tables and using Data Types Aims: To learn how to create tables in Oracle SQL, and how to use Oracle SQL data types in the creation of these tables. Outline of Session: Given a simple database design, decide on suitable data types for all the columns in all the tables of the database. Create the tables using Oracle SQL. Decide what columns must never be allowed to have data missing, and re-create the tables accordingly. From the results of the earlier exercise to determine what sort of data would be needed to run a club or society, decide on 2 specific relations of those discussed, and create SQL tables to represent those relations.

A SIMPLE DATABASE Over the course of this module we will be developing a relational database to represent the activities of a small company which runs various Projects and which has its Employees organised into Departments. Thus we want to create in the database a relation to hold all the related data about Projects, another relation to hold all the related data about Employees, and a third relation to hold all the related data about Departments. Note that SQL uses the term tables for relations, row for tuple and column for attribute, although strictly speaking, the SQL terms do not always mean exactly the same as the relational terms. When differences arise, they will be mentioned. So to create a database, we will actually need to create tables and specify the columns that the tables contain. Consider the information below, which describes what data we want to hold in the Employees, Departments and Projects tables respectively : Table Name Column Name Description Data type EMP EMP_NO A two-character code, not necessarily both digits. EMP_NAME The Employee s surname: up to 10 letters. SALARY Whole number of pounds. MARITAL_STATUS A one-character coded value. DEPT DEPT_NO A two-character code, not necessarily both digits. DEPT_NAME Name of this Department: up to 10 letters. MANAGER_NO The Employee Number of the Manager of this Department. BUDGET Whole number of pounds. PROJ PROJ_NO A two-character code, not necessarily both digits. START_DATE The date when the Project started. DEADLINE Date when the Project must be completed. Exercise: Fill in the right-hand column above with suitable SQL data types. Decide in principle what kind of data should be stored in each column. Then decide what kind of Oracle SQL data type serves your purpose. (You will need to look up available types in an Oracle SQL reference). 2

SQL SYNTAX School of Computing, Engineering and Information Sciences As with other programming languages, there is a precise set of rules governing the syntax (grammar) of SQL. We will present examples of SQL syntax as and when they are needed in this and succeeding exercises. As each SQL construct is introduced, a box containing details of its makeup will be displayed, according to the following conventions: CAPITALS denote reserved words (i.e. part of the vocabulary of SQL with particular meaning within the language). <Angled brackets> contain the name of a syntactic construct that is described elsewhere. underlined italics denote the name of some object within the database (e.g. a table or column name), or a numeric or character-string value as appropriate. Character strings or patterns must be enclosed in single quotation marks. A pattern is similar to a character string but may contain the wild-card characters % (percent) and _ (underscore). Character strings are also known as literals or string constants. [square brackets] denote an optional item. {<option 1> <option 2> <option 3>} vertical bars separate alternative items enclosed by curly brackets (braces). Only one of the alternatives is to be used. The braces may be omitted where the meaning is clear. [ etc.] indicates that the construct immediately before the square brackets may, optionally, be repeated any number of times. If a separator is required it will be shown like this [, etc.] When devising Data Names (e.g. names for tables or columns) remember they must start with a letter, the rest of the name being optionally a mixture of letters, digits and the (hyphen) and _ (underscore) characters. SQL statements run continuously until terminated by a semi-colon, but it can be useful to break a statement into several lines to enhance readability. 3

CREATING TABLES IN ORACLE SQL provides a CREATE TABLE statement for setting up database tables. As a minimum, this requires us to give the table a name and then to specify for each column of the table: its name; the data type of the data values that it is to contain. In its simplest form, the CREATE TABLE statement has the syntax CREATE TABLE table-name ( <column definition> [, etc.] ) ; Following the reserved words CREATE TABLE, the actual name of the table must be supplied. This is followed by a pair of (round) brackets containing one or more instances, separated by commas, of a column definition. The statement ends (as do other SQL statements) with a semi-colon. A column definition, in its simplest form, has the syntax column-name <data type> In plain English, what does this syntax definition mean? The most commonly used data types in Oracle SQL are: INTEGER, i.e. a whole number (which may have a positive or negative value) DECIMAL. This requires you to specify firstly the precision (number of significant figures) and then the number of decimal places e.g. DECIMAL (7, 2) CHAR, i.e. a string of characters. It is necessary to specify the number of characters to be held, e.g. CHAR(10). If less than 10 characters (in this example) are used, then Oracle will add sufficient space characters onto the end of the string such that there is a total of 10 characters. VARCHAR2 1, i.e. a variable length string of characters. It is necessary to specify the maximum number of characters that could be held, e.g. VARCHAR2(10). If less than 10 characters (in this example) are used, then no extra space characters are added. 1 The 2 in VARCHAR2 indicates that it is Oracle s second version of the variable length character type. It has no relevance to how many characters may or should be held in the character string. 4

DATE, which will be formatted according to a standard convention. You should now be able to create all three tables, EMP, DEPT and PROJ. To get you started, here is the SQL code for creating the EMP table. You should enter the following code into Oracle, and then try the same procedure for the DEPT and PROJ tables. (Remember, you do not need to enter the line numbers!) SQL> CREATE TABLE EMP( 2 EMP_NO CHAR(2), 3 EMP_NAME VARCHAR2(10), 4 SALARY INTEGER, 5 MARITAL_STATUS CHAR(1) 6 ); EDITING SQL STATEMENTS During the course of entering these 3 tables into your database, make a point of learning how to edit SQL statements, both by means of the copy, cut and paste facilities provided by the Oracle DBMS interface, and by means of the editor built into the interface. (Note that this interface is proprietary to Oracle, and therefore may be quite different to those of other SQL DBMSs). CHECKING YOUR WORK Assuming that your CREATE TABLE statements were syntactically correct, Oracle will have replied to each with the message Table created. However, this is not really sufficient; you need to be able to check that the column names and data types are as you intended. It is possible to do this by means of the DESCRIBE command. This is not an SQL statement but a command which is specific to Oracle, and it does not need a semi-colon after it. Here is an example of its use : SQL> DESCRIBE EMP Name Null? Type ------------------------------- -------- ---- EMP_NO CHAR(2) EMP_NAME VARCHAR2(10) SALARY NUMBER(10) MARITAL_STATUS CHAR(1) 5

Exercise: Some of the data types shown in the output from DESCRIBE will differ somewhat from what you originally typed in. What examples of this can you find? This is because the data types used by Oracle differ somewhat from those stipulated by the SQL Standard. Nevertheless Oracle does recognise the Standard data types, and these are what we are recommending you to use. If at any time you want to check what tables you have in your database, you can use the following SQL statement : SELECT * FROM cat ; This will give you a list, by table name, of all the tables in your database. cat is short for catalog (note the American spelling). Every DBMS uses a database catalog(ue) or data dictionary or meta database the terms vary depending on the prevailing DBMS vendor and computing fashion to hold data about the database. (SQL normally uses the term catalog ). All the above query is actually doing is retrieving the contents of the table catalog, wherein is stored the list of table names that we want. catalog is one of the tables in the database catalog(ue) as a whole. The DESCRIBE command works by executing a more sophisticated retrieval on parts of the overall database catalog(ue). DECIDING ON NULLS The tables created so far permit data to be missing from rows in every column of every table; i.e. allow NULLs to appear there instead. In practice, this would often be unacceptable. Therefore review all the columns in all the tables, and decide which columns must always have a value in every row of the table; in other words, for these columns there can never be any exceptions, and every row must always have a value of the required type in that column. For example, in the PROJ table, it is reasonable to say that every row must have a START_DATE value, since we will not put a row in the table to represent a real-world project until we know when it will start (and hence that it definitely will start). However DEADLINE values may sometimes be missing because realistically we are not always certain when a project should finish until some considerable way through it; hence the DEADLINE column may have NULLs as well as deadline dates. Exercise: For each column in the 3 tables, decide whether NULLs are permissible or not. For each column, enter your conclusion in the right-hand page margin opposite the 6

column s name in the tabular design summary on page 2; then summarise your rationale for each column below : Having decided on which columns must never contain NULLs, you will need to amend the SQL table definitions to accomplish this. There are two ways to do this : 1. Drop a table (i.e. eliminate or delete it from the database) and recreate it to its new specification. 2. Alter the table appropriately. In principle, the second way is simpler, and indeed may be the only practicable way if data is stored in the table. However it uses the SQL ALTER TABLE command, which can be complex to use until you have mastered all the ramifications of specifying and creating tables. Therefore we postpone consideration of the ALTER TABLE command until later in the course, and use the first method instead; our tables contain no data yet, so this is not a problem. So get rid of all 3 tables from the database. Use the SQL command DROP TABLE table-name ; where table-name is the name of the table to be dropped or got rid of. Then re-create the 3 tables with the appropriate NON NULL columns. The syntax to be used when specifying that a column cannot contain NULLs is simply to put the phrase NOT NULL after the column s data type. Thus the formal syntax of a column specification within a CREATE TABLE statement is : 7

column-name <data type> [ NOT NULL ] Remember [ and ] denote an option in the syntax do not enter them. FURTHER EXERCISES Refer back to the previous exercise where you developed some relations that would form a useful database for a club or society. Select at least 2 of those relations, and : 1. Decide on a name for each relation. 2. For each attribute in each relation, decide on an attribute name and data type, and whether it must always hold a data value or whether missing data would be allowed. 3. Derive an SQL CREATE TABLE statement to create the SQL equivalent of each relation, and enter it into your database. 4. Check in the Oracle SQL catalog(ue) whether you have created the tables correctly or not. If they contain any errors, drop them and recreate them. 8