introduction to sql, sql*plus

32
Introduction to SQL, SQL*Plus, and SQL Developer

Upload: chhom-karath

Post on 28-Jan-2018

380 views

Category:

Education


0 download

TRANSCRIPT

Introduction to SQL, SQL*Plus,and SQL Developer

PL/SQL Development Environments• PL/SQL is designed to meet such requirements. It provides a programming

extension to the already-existing SQL.

• Oracle provides several tools that can be used to write PL/SQL code. Some of the development tools that are available for use in this course:

– Oracle SQL Developer: A graphical tool, is a free graphical tool that enhances productivity and simplifies database development tasks. connect to any target Oracle database schema using standard Oracle database authentication.

– Oracle SQL*Plus: A window or command-line application

– Oracle JDeveloper: A window-based integrated development environment (IDE), allows developers to create, edit, test, and debug PL/SQL code by using a sophisticated GUI. Oracle JDeveloper is a part of Oracle Developer Suite and is also available as a separate product.

Overview of SQL• Structured Query Language (SQL) is the set of statements with which all

programs and users access data in an Oracle database.

• Application programs and Oracle tools often allow users access to the database without using SQL directly.

• SQL is a language you can use in (at least) two different ways: interactively or embedded.

– Using SQL interactively means that you enter SQL commands via a keyboard, and you get the command results displayed on a terminal or computer screen.

– Using embedded SQL involves incorporating SQL commands within a program in a different programming language (such as Java or C).

• Although SQL is called a query language, its possibilities go far beyond simply data retrieval. Normally, the SQL language is divided into the following four command categories:

1. Data definition (Data Definition Language, or DDL)

2. Data manipulation (Data Manipulation Language, or DML)

3. Retrieval

4. Security and authorization

•The Oracle database for executing stored subprograms• The Oracle Forms client when you run client/server applications, or in the Oracle Application Server when you use Oracle Forms Services to run Forms on the Web

Data Definition• SQL data definition commands allow you to create, modify, and remove

components of a database structure. Typical database structure components are tables, views, indexes, constraints, synonyms, sequences, and so on.

• Almost all SQL data definition commands start with one of the following three keywords:– CREATE, to create a new database object

– ALTER, to change an aspect of the structure of an existing database object

– DROP, to drop (remove) a database object

• One of the strengths of an RDBMS is the fact that you can change the structure of a table without needing to change anything in your existing database application programs.

• For example, you can easily add a column or change its width with the ALTER TABLE command. In modern DBMSs such as Oracle, you can even do this while other database users or applications are connected and working on the database—like changing the wheels of a train at full speed.

Data Manipulation and Transactions• SQL data definition commands allow you to change the structure of a

database, SQL data manipulation commands allow you to change the contents of your database. For this purpose, SQL offers three basic data manipulation commands:

– INSERT, to add rows to a table

– UPDATE, to change column values of existing rows

– DELETE, to remove rows from a table

• You can add rows to a table with the INSERT command in two ways. One way is to add rows one by one by specifying a list of column values in the VALUES clause of the INSERT statement. The other is to add one or more rows to a table based on a selection (and manipulation) of existing data in the database (called a subquery).

Retrieval• The only SQL command used to query database data is SELECT. This command

acts at the set (or table) level, and always produces a set (or table) as its result. If a certain query returns exactly one row, or no rows at all, the result is still a set: a table with one row or the empty table, respectively.

• FROM: Which table(s) is (are) needed for retrieval?

• WHERE: What is the condition to filter the rows?

• GROUP BY: How should the rows be grouped/aggregated?

• HAVING: What is the condition to filter the aggregated groups?

• SELECT: Which columns do you want to see in the result?

• ORDER BY: In which order do you want to see the resulting rows?

Security• SQL offers several commands to implement data security and to restrict data

access. First of all, access to the database must be defined. User authorization is implemented by providing database users a login name and a password, together with some database-wide privileges.

• These are the most important commands in this area:

– CREATE USER, to define new database users

• ALTER USER, to change properties (privileges and passwords) of existing database users

– DROP USER, to remove user definitions from the database

Security• Privileges and Roles

• If users are authorized to access the database, you can implement fine-grained data access by granting specific privileges.

• The Oracle DBMS offers two types of privileges: system privileges and object privileges.

– System privileges pertain to the right to perform certain (nonobject-related) actions; for example, you can have the CREATE SESSION privilege (allows you to log on to the database) and the CREATE TABLE privilege. Oracle supports approximately 140 different system privileges.

– Object privileges involve the right to access a specific database object in a specific way; for example, the right to issue SELECT, INSERT, and UPDATE commands against the EMPLOYEESA table.

Security• The Oracle DBMS allows you to group privileges into roles. Roles make user

management much easier, more flexible, and also more manageable. The following are the corresponding SQL commands used to administer these privileges and roles:

– GRANT, to grant certain privileges or roles to users or roles

– REVOKE, to revoke certain privileges or roles from users or roles

– 33

Basic SQL Concepts and Terminology• Constants (Literals)

– A constant (or literal) is something with a fixed value. We distinguish numbers (numeric constants) and text (alphanumeric constants). In database jargon, alphanumeric constants are also referred to as strings.

– alphanumeric constants (strings) must be placed between single quotation marks (quotes).

– Numbers are also relatively straightforward in SQL; however, don’t put them between quotes or they will be interpreted as strings.

– you can explicitly indicate that you want SQL to interpret numeric values as floating point numbers by adding the suffixes f or d to indicate single (float) or double precision, respectively.

– decimal period and group separators ( (commas) in numbers, because the correct interpretation of these characters depends on the value of a session parameter (NLS_NUMERIC_CHARACTERS), and there are some cultural differences in this area.

– dates and time durations (intervals) are special cases. They are typically specified and represented as alphanumeric constants, but they need something else to distinguish them from regular strings.

Basic SQL Concepts and Terminology• Options to specify date and time-related constants in SQL:

– Specify them as alphanumeric constants (strings) and rely on implicit interpretation and conversion by the Oracle DBMS. Dangerous, because things go wrong if the actual format parameter for that session is different from the format of the string.

– Specify them as alphanumeric constants (strings) and use a CAST or TO_DATE conversion function to specify explicitly how the strings must be interpreted

– Specify them as alphanumeric constants (strings), prefixed with DATE, TIMESTAMP, or INTERVAL. If you use INTERVAL, you also need a suffix to indicate a dimension, such as DAY, MONTH, or YEAR.

Basic SQL Concepts and Terminology

• Note:

– difference between 132 and '132'.

– the SQL language is case-insensitive, alphanumeric constants (strings) are case-sensitive. For example, 'JOneS' is not equal to 'Jones'.

Operators, Operands, Conditions, and Expressions• An operator does something. Operands are the “victims” of operations; that is,

operands serve as input for operators.

• Sometimes, operators need only a single operand (in which case, they are also referred to as monadic operators), but most operators need two or more operands.

• The SQL operators are divided in four categories, where the differentiating factor is the operand datatype:

– Arithmetic operators

– Alphanumeric operators

– Comparison operators

– Logical operators

Arithmetic Operators• apply arithmetic operators only on NUMBER values; however, there are some

exceptions:

– If you subtract two DATE values, you get the difference between those two dates, expressed in days.

– You can add a DATE and an INTERVAL value, which results in another date.

– If you add a DATE and a NUMBER, the number is interpreted as an interval expressed in days.

Scalar Data Type• Hold a single value

• Have no internal component

– CHAR [(maximum_length)]

– VARCHAR2 (maximum_length)

– NUMBER [(precision, scale)]

– BINARY_INTEGER

– PLS_INTEGER

– BOOLEAN

– BINARY_FLOAT

– BINARY_DOUBLE

• Comment in Oracle SQL

– --My text

– --THis is money calculation for riel

– /*

– kadjhfasdjhfkadjfhkadjfh

– adkfaksdfhkdf

– */

Variables• A variable is something that may have a varying value over time, or even an

unknown value. A variable always has a name, so you can refer to it.

• SQL supports two types of variables:

– Column name variables: The name of a column stays the same, but its value typically varies from row to row while scanning a table.

– System variables: These have nothing to do with tables; nevertheless, they can play an important role in SQL. They are commonly referred to as pseudo columns.

VariablesTypes of Variables

• PL/SQL variables:

– Scalar:

– Reference

– Large object (LOB)

– Composite

• Non-PL/SQL variables: Bind variables

Variables• PL/SQL variable has a data type, which specifies a storage format, constraints,

and a valid range of values.

– Scalar data types: Scalar data types hold a single value.

– Reference data types: Reference data types hold values, called pointers, which point to a storage location.

– LOB data types: LOB data types hold values, called locators, which specify the location of large objects (such as graphic images) that are stored outside the table.

– Composite data types: are available by using PL/SQL collection and record variables. PL/SQL collections and records contain internal elements that you can treat as individual variables.

The slide illustrates the following data types:• TRUE represents a Boolean value.• 15-JAN-09 represents a DATE.• The image represents a BLOB.• The text in the callout can represent a VARCHAR2 data type or a CLOB.• 256120.08 represents a NUMBER data type with precision and scale.• The film reel represents a BFILE.• The city name Atlanta represents a VARCHAR2 data type.

Declaring and Initializing PL/SQL Variables• Initialize variables that are designated as NOT NULL and CONSTANT.

• Initialize variables with the assignment operator (:=) or the DEFAULT keyword:

PL/SQL Block Structure• PL/SQL Block Structure

• DECLARE (optional)

– Variables, cursors, user-defined exceptions

• BEGIN (mandatory)

– SQL statements

– PL/SQL statements

• EXCEPTION (optional)

– Actions to perform when exceptions occur

• END; (mandatory)

• A PL/SQL block consists of four sections:

• Declarative (optional): The declarative section begins with the keyword DECLARE and ends when the executable section starts.

• Begin (required): The executable section begins with the keyword BEGIN. This section needs to have at least one statement.

• Exception handling (optional): The exception section is nested within the executable section. This section begins with the keyword EXCEPTION.

• End (required): All PL/SQL blocks must conclude with an END statement. Observe that

• END is terminated with a semicolon.

Variables+ EX1:

• Initialize variables with the assignment operator (:=) or the

• DEFAULT keyword:

v_myName VARCHAR2(20):='John';

v_myName VARCHAR2(20) DEFAULT 'John';

+ Ex2:

DECLARE

v_myName VARCHAR2(20);

BEGIN

DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName);

v_myName := 'John';

DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName);

END;

+ Ex3:

DECLARE

v1 CONSTANT NUMBER(6,2):=10.555667;

BEGIN

v1:=300;

DBMS_OUTPUT.PUT_LINE(v1);

END;

Variables• Use of Variables

• Variables can be used for:Temporary storage of data, Manipulation of stored values,Reusability.

• Requirements for Variable Names

– Must start with a letter

– Can include letters or numbers

– Can include special characters (such as $, _, and #)

– Must contain no more than 30 characters

– Must not include reserved words

Syntax:Examples:identifier [CONSTANT] datatype [NOT NULL][:= | DEFAULT expr];DECLAREv_hiredate DATE;v_deptno NUMBER(2) NOT NULL := 10;v_location VARCHAR2(13) := 'Atlanta';c_comm CONSTANT NUMBER := 1400;

Scalar Data Type• Hold a single value

• Have no internal component

– CHAR [(maximum_length)]

– VARCHAR2 (maximum_length)

– NUMBER [(precision, scale)]

– BINARY_INTEGER

– PLS_INTEGER

– BOOLEAN

– BINARY_FLOAT

– BINARY_DOUBLE

• Comment in Oracle SQL

– --My text

– --THis is money calculation for riel

– /*

kadjhfasdjhfkadjfhkadjfh

adkfaksdfhkdf

*/

Create Table• CREATE Table Statemet

• Syntax:

CREATE TABLE tb_Name(

column1 datatype [Null | NOT NULL],

column2 datatype [Null | NOT NULL],

.........

columnN datatype [Null | NOT NULL]

);

EX1: CREATE TABLE TBPRODUCT

(

PRODUCTID NUMBER NOT NULL

, PRODUCTNAME VARCHAR2(20) NOT NULL

, QTY INT

, UNITPRICE FLOAT

, DATEIN DATE

, CONSTRAINT TBPRODUCT_PK PRIMARY KEY

(

PRODUCTID

)

ENABLE

);

EX2: CREATE TABLE tbEmployee(EmpID NUMBER(10) NOT NULL,EmpName VARCHAR2(50) NOT NULL,Gender VARCHAR(20) NOT NULL,Address VARCHAR(30) NULL,DOB DATE NOT NULL,CONSTRAINT TBEmployee_PK PRIMARY KEY(EmpID

)ENABLE

);Ex3:CREATE TABLE TBSALEDETAIL (INVOICEID NUMBER NOT NULL

, PRODUCTID NUMBER NOT NULL , UNITPRICE NUMBER NOT NULL , QUANTITY NUMBER NOT NULL , DISCOUNT NUMBER , CONSTRAINT TBSALEDETAIL_PK PRIMARY KEY (INVOICEID

, PRODUCTID )ENABLE

);

Data Modeler

Edit=AlterEx1: ALTER TABLE TBCUSTOMER

ADD (SSID VARCHAR2(20) );

Ex2: ALTER TABLE TBCUSTOMER

MODIFY (ADDRESS NOT NULL);

ALTER TABLE TBCUSTOMER

MODIFY (DOB NOT NULL);

EX3:ALTER TABLE TBEMPLOYEE

MODIFY (EMPNAME DEFAULT Chan Dara );

EX4:ALTER TABLE tbEmployee

ADD (SSID VARCHAR2(20) NOT NULL);

EX5:ALTER TABLE TBPRODUCT

DROP COLUMN DATEIN;

EX6:ALTER TABLE TBPRODUCT

DROP CONSTRAINT TBPRODUCT_PK;

EX7:ALTER TABLE TBPRODUCT

ADD CONSTRAINT TBPRODUCT_PK PRIMARY KEY

(

PRODUCTID

)

ENABLE;

Ex8:ALTER TABLE TBPRODUCT RENAME COLUMN QTY TO QUANTITY;EX9:ALTER TABLE TBPRODUCT MODIFY (PRODUCTNAME CHAR(50) );

ALTER TABLE TBPRODUCT MODIFY (UNITPRICE NUMBER DEFAULT '0' );

Drop TableEX1: drop table "SYSTEM"."TABLE1"

EX2: Rename

alter table "SYSTEM"."TBPRODUCT" rename to tbProducts;