0% found this document useful (0 votes)
121 views13 pages

LAB # 01 Introduction To SQL: Objective

This document provides an introduction and overview of SQL (Structured Query Language) including its components, how to use Oracle SQL*Plus, creating and modifying database tables, and basic SQL commands. SQL is a standard language for querying and modifying relational databases and includes components for data structure, data types, operators, and languages for data query, manipulation, definition, and control. The document demonstrates how to create tables in a database by defining column names and data types.

Uploaded by

zulfiqar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
121 views13 pages

LAB # 01 Introduction To SQL: Objective

This document provides an introduction and overview of SQL (Structured Query Language) including its components, how to use Oracle SQL*Plus, creating and modifying database tables, and basic SQL commands. SQL is a standard language for querying and modifying relational databases and includes components for data structure, data types, operators, and languages for data query, manipulation, definition, and control. The document demonstrates how to create tables in a database by defining column names and data types.

Uploaded by

zulfiqar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Database Management System

LAB # 01

Introduction to SQL
OBJECTIVE:
 What is SQL?
 SQL Language Components
 How To Start With Oracle Sql *Plus
 Creation Of Table In Database
 Insert values in Table
 Modify Table Structure
 Rename table
 Delete Operation

SQL INTRODUCTION

SQL (Standard Query Language) is a database sublanguage for querying and modifying relational
databases. It is a Commercial Database Language. It was developed by IBM Research in the mid
70's and standardized by ANSI in 1986. SQL is followed as a De facto standard.

SQL Language Components

SQL language has several parts:

 Data Structure
 SQL Data Types
 SQL Operators
 Data Query language (DQL)
 Data Manipulation Language (DML)
 Data Definition Language (DDL)
 Data Control Language (DCL)

1
Database Management System

How To Start With Oracle Sql *Plus

In Windows 8, find the Oracle Software and click on SQL Plus. You will be prompted for your
userid, password, hoststring. Enter the information indicated in the prompted window. If the
information provided is valid, you will be provided with the platform displaying SQL> prompt.

1. SQL Plus Commands

Introduction

At the SQL prompt, you can begin typing any SQL command. Upon hitting return (i.e., enter key)
the SQL prompt will change to the line number prompts. When you are finished with typing a SQL
command (query), RUN to execute the SQL command.

Terminate the SQL command with a semicolon at the end that will execute the command
immediately after hitting return. In addition to SQL commands, /, and RUN, other commands can
be issued at the SQL prompt (a semicolon does not have to follow the non SQL commands).

 DESCRIBE tablename--lists the attributes and their specifications of tablename


 EDIT--Places you in an editor (Notepad). The buffer contents are put into the editor
 GET filename--Retrieves a file and places it into the buffer
 SAVE filename--Saves the buffer to the name file
 CLEAR BUFFER--Clears the buffer

Line Editing
One way to change an SQL statement in the buffer is by using the line editor. The following are a
list of line edit commands.

 LIST or L--Lists the contents of the buffer


 LIST n or L n--Lists the contents of line number n in the buffer and makes the line current
 LIST * or L *--Lists the current line
 LIST m n--Lists the range from m to n line
 Append text or A text--Adds to the end of the current line (e.g., "A ," adds a comma to the
end of line
 INPUT or I--Adds one or more lines after the current line so you can begin adding the text.
 CHANGE /text--Deletes text from the current line
 CHANGE /oldtext/newtext--Replaces oldtext with newtext in the current line
 DEL -- Deletes the current line

2
Database Management System

Using Notepad for Editing

You can use Notepad to edit the contents of the buffer. There are two ways to enter Notepad.

 Use the menus Edit/editor/invoke. In addition here, you can use Edit/editor/define to change
the editor. You might check Edit/editor/define prior to editing a buffer to make sure it is set
up the way you would like.
 Type Edit at the SQL Prompt

When you are finished editing, click on File/exit (in Notepad). Next, type GET buffer name at
the SQL prompt. The buffer name will be listed a few lines up in SQL Plus upon returning to SQL
Plus. Type RUN, to execute the command.

Notepad can also be used to save the buffer contents. Use File/Save As to create a permanent
file.

Multiple SQL commands can be typed in Notepad. End each SQL command (except the last
one) with a semicolon. After exiting notepad, type Start buffer name instead of GET buffer name to
run all of the commands. Start filename can also be used to execute SQL command that is stored in
a file.

Sending the Results to a File

To send queries and their results to a file for later printing (e.g., turning in homework assignments), the spool
command is used. On the menu go to FILE/Spool to begin spooling--it will ask for a file name. To quit
spooling, go to FILE/Spool and then click on end Spool.

Retrieving a File

To retrieve SQL command from a file use GET filename or START filename. GET filename places
the file into the buffer. START filename executes the commands in the file.

The SPOOL Command 

The SPOOL command causes SQL*Plus to write the results to a file.

SQL> spool /tmp/myfile.lst

Once spool is set, it will continue to spool the output until the command SPOOL OFF. Note that the
file cannot be seen or used until the SPOOL OFF command.

The @ command tells SQL*Plus to execute a file.  The @@ command is used to run a nested script
that is located in the same directory as the outer scripts.  You can run a nested script with the @
command, but you must fully qualify the file name.

3
Database Management System

2. Language Structure

SQL is a version of Relational Calculus. The basic structure in SQL is the statement.

SQL is a keyword based language. Each statement begins with a unique keyword. SQL
statements consist of clauses which begin with a keyword. SQL syntax is not case sensitive.
Semicolons separate multiple SQL statements.

The other lexical elements of SQL statements are:

 names -- names of database elements: tables, columns, views, users, schemas; names must
begin with a letter (a - z) and may contain digits (0 - 9) and underscore (_)
 literals -- quoted strings, numeric values, datetime values
 delimiters -- + - , ( ) = <><= >= <> . * / || ? ;

Basic database objects (tables, views) can optionally be qualified by schema name. A dot -- ".",
separates qualifiers:

schema-name.table-name

Column names can be qualified by table name with optional schema qualification.

Note: Names can be case sensitive and contain spaces and other delimiters and can use keywords,
by surrounding them with double quotation marks ("). For example,

"1 Name w/spaces"


"SELECT"

Quoted names must match exactly on case.

3. Legal Data Types


VARCHAR2 (size)

Variable length character string having max. Length of size

CHAR (size)

Fixed length character string with number of bytes equal to size

NUMBER (p,s)

Number having a precision p and s digits to the right of the decimal. If you leave off p and s (e.g.,
NUMBER), then it is a floating point number.

4
Database Management System

LONG

Character data of variable length up to 2 gigabytes (cannot be a key)

DATE

A date field

RAW (size)

Raw binary data of length size. Max. size is 255 bytes

LONG RAW

Raw binary data up to 2 gigabytes (cannot be a key)

SQL Table

The database table columns (called also table fields) have their own unique names and have a pre-
defined data types. Table columns can have various attributes defining the column functionality (the
column is a primary key, there is an index defined on the column, the column has certain default
value, etc.).

While table columns describe the data types, the table rows contain the actual data for the columns.

Here is an example of a simple database table, containing customers’ data. The first row, listed in
bold, contains the names of the table columns:

Table: Customers

FirstName LastName Email DOB Phone

John Smith [email protected] 2/4/1968 626 222-2222

Steven Goldfish [email protected] 4/4/1974 323 455-4545

Paula Brown [email protected] 5/24/1978 416 323-3232

James Smith [email protected] 20/10/1980 416 323-8888

SQL Database Tables are the foundation of every RDBMS (Relational Database Management
System).

Creating Tables

Tables can be created using CREATE TABLE statement.

5
Database Management System

The following statement is how you would create a product table.

CREATE TABLE product


(product_id NUMBER(8) NOT NULL, name VARCHAR(20) NOT NULL,
description VARCHAR2(45), price NUMBER(7,2) DEFAULT 00.00, cost
NUMBER(7,2));

To create a new table, type the create table followed by table name and open parenthesis.  All the
columns must be defined within the open and close parenthesis.  Make sure that the last thing is
semicolon.  The name, data type and data size are essential for every column.

When creating a table, you must assign a data type to each column to specify what kind of data
should be stored in this field. Data types dedicate amount of storage space allocated and provide for
a means of error checking. 

Some data types are NUMBER, DATE, CHAR, VARCHAR2 and LONG.  Note that product_id
and name are required and price has default value.  Here is an interpretation of the data type used.

NUMBER(8) - 8 digit integer number.

VARCHAR2(20) - Variable-Length character string up to 20 bytes long. If the data is less than 20
characters, extra characters will not be stored. It will just store number of characters up to 20.

NUMBER(7,2) - 7 digit number with two decimal points.

NOT NULL - Specifies that this row must have value. If violated the table will not be created.
DEFAULT - Specifies default value for this column.  Unpopulated rows are always NULL but this
is just to show default value can be provided. 

We can normalize or put constraints on the SQL table by defining the primary and foreign keys. 
Here are two tables that have primary/foreign keys relationship.

CREATE TABLE employees ( ENO CHAR(2) PRIMARY


KEY, E_FIRSTNAME CHAR(15) NOT NULL, CREATE TABLE department
E_LASTNAME CHAR(15) NOT NULL, E_AGE  ( department_id NUMBER(8),
CHAR(4),DEPARTMENT_NAME CHAR (15), SALARY name VARCHAR(20) );
DECIMAL(7,2), JOBTITLE CHAR (15) );

6
Database Management System

DATA TYPES

When creating a table, you must assign a data type to each column to specify what kind of data
should be stored in this field. Data types dedicate amount of storage space allocated and provide for
a means of error checking.

For example, if price field is declared as a number field, it will not accept string values and vice
versa.   Some data types are NUMBER, DATE, CHAR, VARCHAR2, CLOB, NCHAR,
NVARCHAR2, NCLOB, and LONG.

CHAR(n) declares fixed length character string data type. It's good to use when the data is one
character for example "m" or "f" other wise it wastes memory. For example, if CHAR(20) is
specified and 3 character data is provided, it will still use all the 20 bytes by adding trailing spaces.

 VARCHAR2(n) declares variable length character string data type. It eliminates all the
trailing spaces. For example, if VARCHAR2(20) is specified and 3 character data is
provided, it will only use 3 bytes and no memory wasted. Accepts up to 4000 bytes long.

 NUMBER(n) stores number data type both in fixed and floating points. It can store the
range from 10^-130 to 10^126. NUMBER(p)means just digits, for example NUMBER(8)stores
8 digits.  

NUMBER (p,s) stores digits and decimals. For example, NUMBER(8,2) will store 8 digits
and 2 decimals.

 DATE stores a date value in century, year, month, day, hour, minute, and second format.
Stores dates in the range of January 1, 4712BC to December 31, 4712 AD

 LONG stores variable length character string up to 4 gigabytes long. Used when working
with large amount of text values.

 CLOB stores variable length character string up to 2 gigabytes long. Twice the size of long.

 NCHAR NVARCHAR2stores the data in Unicode format instead of ASCII format.

7
Database Management System

Altering Tables

ALTER TABLE statement will allow you to add new column or constraint, modify existing column
or constraint, and drop existing column or existing constraint after the table is created.  The
following statement will add a middle name column to the employees table.

ALTER TABLE employees


     ADD middle_name VARCHAR2(25);
 

The statement bellow modifies the last_name to required column. This statement works when there
no null last name exists now.

ALTER TABLE employees


     MODIFY last_name NOT NULL;

This statement deletes the above column.

ALTER TABLE employees


     DROP COLUMN last_name;

INSERT STATEMENT

We created the table, define the constraints and now they are ready to be populated with data. 
INSERT command is used to populate the table with records.  Here is a statement that adds a row or
record to product table.  This type of statement needs all the columns to be exact order.  This is a
poor way to insert values into a table.

INSERT INTO product


VALUES('10000000', 'Printer', 'Inkjet colour Printer', '120', '80');

  Here is a more favorable and controllable way to insert values into the a table.

INSERT INTO product (product_id, name, description, price, cost)


VALUES ('10000000','Printer', Inkjet colour printer','120','80');

8
Database Management System

Renaming Tables

The syntax to rename table is:

RENAME <TABLE NAME> TO <NEW TABLE NAME>

Example:

RENAME BUSINESS TO INCOME;

Delete Operations
The DELETE command deletes rows from the table that satisfies the condition provided by its
where clause, and returns the number of records deleted.

If a DELETE statement without a WHERE clause is issued then, all rows are deleted.

The verb DELETE in SQL is used to remove either:

All the rows from a table

OR

A set of rows from a table

Removal of All Rows

Syntax:
DELETE FROM <Tablename>

Example:
DELETE FROM CUSTOMERS;

Removal of specific row

Syntax:
DELETE FROM <TABLE NAME> WHERE <CONDITION>;

Example:
DELETE FROM BILLS WHERE BILLDT<‘01-Aug-2000’;

9
Database Management System

Dropping Tables

To remove a table from the database use

DROP TABLE tablename

LAB TASKS
LAB TASK 1
Create a table with name “EMPLOYEE” with following attributes:

Employee ID

First Name

Last Name

Age

Department Name

Salary

Job Title

LAB TASK 2
 Create the table as described below:

Table Name: CLIENT_MASTER (used to store client information)

10
Database Management System

 Insert the following data into the respective table

LAB TASK 3
 Create the table as described below:

Table Name: SALES_ORDER (used to store client’s order)

11
Database Management System

 Insert the following data into the respective tables

LAB TASK 4
Delete from CLIENT_MASTER where the column state holds the value “Federal”.

LAB TASK 5

12
Database Management System

Add a column called “TELEPHONE” of data type ‘Number’ and ‘Size’ = 10 to the
CLIENT_MASTER table.

LAB TASK 6
Change the name of the CLIENT_MASTER table to “CLIENT_INFORMATION”.

13

You might also like