LAB # 01 Introduction To SQL: Objective
LAB # 01 Introduction To SQL: Objective
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.
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
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.
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).
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.
2
Database Management System
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.
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.
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.
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,
CHAR (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
DATE
A date field
RAW (size)
LONG RAW
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
SQL Database Tables are the foundation of every RDBMS (Relational Database Management
System).
Creating Tables
5
Database Management System
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.
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.
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.
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.
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.
The statement bellow modifies the last_name to required column. This statement works when there
no null last name exists now.
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.
Here is a more favorable and controllable way to insert values into the a table.
8
Database Management System
Renaming Tables
Example:
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.
OR
Syntax:
DELETE FROM <Tablename>
Example:
DELETE FROM CUSTOMERS;
Syntax:
DELETE FROM <TABLE NAME> WHERE <CONDITION>;
Example:
DELETE FROM BILLS WHERE BILLDT<‘01-Aug-2000’;
9
Database Management System
Dropping Tables
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:
10
Database Management System
LAB TASK 3
Create the table as described below:
11
Database Management System
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