Detailed introduction to Oracle sqlplus commands

Source: Internet
Author: User

1. Oracle startup and Shutdown
1. to enable or disable the Oracle System in a single-host environment, you must first switch to the Oracle user, as shown below:
Su-Oracle

A. Start the Oracle System
Oracle> svrmgrl
Svrmgr> connect internal
Svrmgr> startup
Svrmgr> quit

B. Disable the Oracle system.
Oracle> svrmgrl
Svrmgr> connect internal
Svrmgr> Shutdown
Svrmgr> quit

Run the following command to start the Oracle9i database:
$ Sqlplus/nolog

SQL * Plus: Release 9.2.0.1.0-production on Fri Oct 31 13:53:53 2003

Copyright (c) 1982,200 2, Oracle Corporation. All rights reserved.

SQL> connect/As sysdba
Connected to an idle instance.
SQL> startup ^ C

SQL> startup
Oracle instance started.

2. to enable or disable the Oracle System in a dual-host environment, you must first switch to the root user, as shown below:
Su-Root

A. Start the Oracle System
Hareg-y Oracle

B. Disable the Oracle system.
Hareg-N Oracle

Oracle Database startup Methods

Note:

There are several startup methods:
1. startup nomount
Non-installation startup. In this mode, you can execute: re-build the control file and re-build the database.

Read the init. ora file and start the instance, that is, start the SGA and background processes. To start the process, you only need the init. ora file.

2. startup Mount dbname
Install and start. In this mode, run:
Database Log archiving,
Database media recovery,
Online or offline data files,
Locate the data file and redo the log file.

Execute "nomount", open the control file, and confirm the location of the data file and the on-line log file,
However, data files and log files are not verified at this time.

3. startup open dbname
Run "nomount" first, then "Mount", and then open all database files including the redo log file,
In this way, you can access data in the database.

4. startup, which is equal to the following three commands
Startup nomount
Alter database Mount
Alter database open

5. startup restrict
Constraint-based startup
This method can start the database, but only allow access by users with certain privileges
When a non-authorized user accesses the service, the following prompt is displayed:
Error:
ORA-01035: Oracle only allows users with restricted session Permissions

6. startup force
Force start Mode
When the database cannot be closed, you can use startup force to close the database.
Shut down the database first, and then execute the normal database startup command

7. startup pfile = parameter file name
Startup method with initialization parameter file
Read the parameter file first, and then start the database according to the settings in the parameter file.
Example: startup pfile = E: oracleadminoradbpfileinit. ora

8. startup exclusive

2. How can users effectively use data dictionaries?

Oracle Data dictionary is an important part of a database. It is generated with the database and changes with the database changes,

It is reflected in some tables and Views under the Sys user. The data dictionary name is an uppercase English character.

The data dictionary contains user information, user permission information, all data object information, table constraints, and views of the statistical analysis database.
We cannot manually modify the information in the data dictionary.

Generally, oracle users do not know how to use it effectively.

The name and interpretation of all data dictionary tables. It has a synonym, dict.
Dict_column field names and explanations in all data dictionary tables

To query index-related data dictionaries, use the following SQL statement:

SQL> select * From dictionary where instr (comments, 'index')> 0;

If you want to know the detailed meaning of each field name in the user_indexes table, you can use the following SQL statement:

SQL> select column_name, comments from dict_columns where table_name = 'user _ indexes ';

You can easily know the detailed name and explanation of the data dictionary without viewing other Oracle documents.

The following describes how to use common data dictionaries for oracle users by category.

1. User

View the default tablespace of the current user
SQL> select username, default_tablespace from user_users;

View the role of the current user
SQL> select * From user_role_privs;

View the system and table-level permissions of the current user
SQL> select * From user_sys_privs;
SQL> select * From user_tab_privs;

2. Tables

View All tables under a user
SQL> select * From user_tables;

View tables whose names contain log characters
SQL> select object_name, object_id from user_objects
Where instr (object_name, 'log')> 0;

View the creation time of a table
SQL> select object_name, created from user_objects where object_name = upper ('& table_name ');

View the size of a table
SQL> select sum (bytes)/(1024*1024) as "size (m)" from user_segments
Where segment_name = upper ('& table_name ');

View the table in the Oracle memory Partition
SQL> select table_name, cache from user_tables where instr (cache, 'y')> 0;

3. Index

View the number and category of Indexes
SQL> select index_name, index_type, table_name from user_indexes order by table_name;

View indexed fields
SQL> select * From user_ind_columns where index_name = upper ('& index_name ');

View index size
SQL> select sum (bytes)/(1024*1024) as "size (m)" from user_segments
Where segment_name = upper ('& index_name ');

4. Serial number

View the serial number. last_number is the current value.
SQL> select * From user_sequences;

5. View

View view name
SQL> select view_name from user_views;

View the SELECT statement for creating a view
SQL> set view_name, text_length from user_views;
SQL> set long 2000; Description: You can set the size of set long based on the text_length value of the view.
SQL> select text from user_views where view_name = upper ('& view_name ');

6. Synonyms

View synonym name
SQL> select * From user_synonyms;

7. Constraints

View the constraints of a table
SQL> select constraint_name, constraint_type, search_condition, r_constraint_name
From user_constraints where table_name = upper ('& table_name ');

SQL> select C. constraint_name, C. constraint_type, CC. column_name
From user_constraints C, user_cons_columns CC
Where C. Owner = upper ('& table_owner') and C. table_name = upper ('& table_name ')
And C. Owner = cc. Owner and C. constraint_name = cc. constraint_name
Order by CC. position;

8. storage functions and processes

View the status of functions and processes
SQL> select object_name, status from user_objects where object_type = 'function ';
SQL> select object_name, status from user_objects where object_type = 'Procedure ';

View functions and processesSource code
SQL> select text from all_source where owner = user and name = upper ('& plsql_name ');

Iii. View Database SQL

1. view the table space name and size.

Select T. tablespace_name, round (sum (Bytes/(1024*1024), 0) ts_size
From dba_tablespaces T, dba_data_files d
Where T. tablespace_name = D. tablespace_name
Group by T. tablespace_name;

2. view the name and size of the tablespace physical file.

Select tablespace_name, file_id, file_name,
Round (Bytes/(1024*1024), 0) total_space
From dba_data_files
Order by tablespace_name;

3. Check the rollback segment name and size.

Select segment_name, tablespace_name, R. status,
(Initial_extent/1024) initialextent, (next_extent/1024) nextextent,
Max_extents, V. curext curextent
From dba_rollback_segs R, V $ rollstat v
Where R. segment_id = V. USN (+)
Order by segment_name;

4. View Control Files

Select name from V $ controlfile;

5. view log files

Select member from V $ logfile;

6. View table space usage

Select sum (bytes)/(1024*1024) as free_space, tablespace_name
From dba_free_space
Group by tablespace_name;

Select a. tablespace_name, A. bytes total, B. bytes used, C. bytes free,
(B. bytes * 100)/A. bytes "% used", (C. bytes * 100)/A. bytes "% free"
From SYS. sm $ ts_avail A, SYS. sm $ ts_used B, SYS. sm $ ts_free C
Where a. tablespace_name = B. tablespace_name and A. tablespace_name = C. tablespace_name;

7. view database objects

Select owner, object_type, status, count (*) Count # From all_objects group by owner, object_type, status;

8. view the database version

Select version from product_component_version
Where substr (product, 1, 6) = 'oracle ';

9. view the database creation date and archiving method

Select created, log_mode, log_mode from V $ database;

Iv. Oracle user connection management

Use the system administrator to check whether the current database has several user connections:

SQL> select username, Sid, serial # from V $ session;

If you want to stop a connection

SQL> alter system kill session 'sid, serial #';

If this command does not work, find the number of UNIX processes.

SQL> select pro. spid from V $ session SES, V $ process pro where SES. Sid = 21 and SES. paddr = pro. ADDR;

Note: 21 is the number of SID of a connection.

Then run the kill command to kill the process number.

V. use SQL * Plus

A. Near-entry SQL * Plus
$ Sqlplus user name/Password

Exit SQL * Plus
SQL> exit

B. Get help information under sqlplus
List all SQL commands and SQL * Plus commands
SQL> help
Lists information about a specific command.
SQL> HELP command name

C. Describe
SQL> DESC table name

D. Edit commands in SQL * Plus
Display SQL Buffer commands
SQL> L

Modify SQL commands
First, change the row to be corrected to the current row.
SQL> N
Use the change command to modify the content
SQL> C/old/new
Confirm whether it is correct
SQL> L

You can use the input command to add one or more rows in the SQL Buffer.
SQL> I
SQL> input content

E. Call the external system editor.
SQL> edit file name
You can use the define command to set the system variable editor to change the type of the text editor. In the login. SQL file, define the following line:
Define_editor = vi

F. Run the command file
SQL> Start test
SQL> @ Test

Common SQL * Plus statements
A. create, modify, and delete tables
The command format for creating a table is as follows:
Create Table Name (column description list );

The command to add a new column to the base table is as follows:
Alter table table name Add (column description list)
For example, add an age column to the test table to store the age.
SQL> ALTER TABLE Test
Add (age Number (3 ));

The command to modify the definition of a base table column is as follows:
Alter table table name
Modify (column name data type)
For example, the width of the count column in the test table is extended to 10 characters.
SQL> alter atble Test
Modify (county char (10 ));

B. The statement format for deleting a table is as follows:
Dorp table name;
For example, deleting a table deletes both the table data and table definitions.
SQL> drop Table Test

C. Create and delete tablespaces

Vi. Sh file for Oracle logical backup

Full backup sh file: exp_comp.sh

RQ = 'date + "% m % d "'

Su-Oracle-c "exp system/manager full = y inctype = complete file =/Oracle/export/db_comp $ RQ. dmp"

Cumulative backup sh file: exp_cumu.sh

RQ = 'date + "% m % d "'

Su-Oracle-c "exp system/manager full = y inctype = cumulative file =/Oracle/export/db_cumu $ RQ. dmp"

Sh file for Incremental Backup: exp_incr.sh

RQ = 'date + "% m % d "'

Su-Oracle-c "exp system/manager full = y inctype = incremental file =/Oracle/export/db_incr $ RQ. dmp"

Root User crontab file
/Var/spool/cron/crontabs/root Add the following content

0 2 1 **/Oracle/exp_comp.sh

30 2 ** 0-5/Oracle/exp_incr.sh

45 2 ** 6/Oracle/exp_cumu.sh

Of course, this timetable can be changed according to different requirements. This is just an example.

VII. Common SQL syntax and Data Objects in Oracle

I. Data Control Statement (DML)

1. insert (insert the record statement into the data table)

Insert into Table Name (field name 1, field name 2 ,......) Values (value 1, value 2 ,......);
Insert into Table Name (field name 1, field name 2 ,......) Select (field name 1, field name 2 ,......) From another table name;

Field Values of the string type must be enclosed in single quotes, for example, 'good Day'
If the field value contains single quotes and requires String Conversion, we replace it with two single quotes ''.
An error occurs when the value of a string type field exceeds the defined length. It is best to verify the length before insertion.

The field value of the date field can use the system time sysdate of the current database, accurate to seconds
Or use a string to convert to the date type function to_date ('2017-08-01 ', 'yyyy-MM-DD ')
To_date () has many date formats. For more information, see Oracle Doc.
-Month-day hour: minute: seconds format YYYY-MM-DD hh24: MI: SS

The maximum length of a string that can be operated during insert is less than or equal to 4000 single bytes. To insert a longer string, use the clob type for the field,
Use dbms_lob in OracleProgramPackage.

If you want to use a serial number that automatically increases from 1 during insert, you should first create a serial number
Create sequence serial number name (preferably table name + Serial number mark) increment by 1 start with 1
Maxvalue 99999 cycle nocache;
The maximum value is determined by the length of the field. If the defined auto-increment serial number (6), the maximum value is 999999.
Insert statement insert this field value: name of the serial number. nextval

2. Delete (delete the statements recorded in the data table)

Delete from table name where condition;

Note: deleting a record does not release the occupied data block tablespace in Oracle. It only marks the deleted data blocks as unused.

To delete all records in a large table, run the truncate command to release the occupied data block tablespace.
Truncate table name;
This operation cannot be rolled back.

3. Update (modify the statements recorded in the data table)

Update table name set field name 1 = value 1, field name 2 = value 2 ,...... Where condition;

If the modified value n is not assigned a value or defined, the original record content will be cleared to null. It is best to perform non-null verification before modification;
An error occurs when the value of N exceeds the defined length. It is best to verify the length before insertion ..

Note:
A. The preceding SQL statements have row-level locks applied to tables,
After confirmation, you must add the Transaction Processing Command commit to take effect,
Otherwise, the changes may not be written into the database.
To recall these operations, run the rollback command to restore them.

B. Estimate the range of records that may be operated before running insert, delete, and update statements,
It should be limited to a small range (10 thousand records). Otherwise, Oracle will use a large rollback segment to process this transaction.
Slow program response or even loss of response. If more than 100,000 of these operations are recorded, you can complete these SQL statements in multiple parts,
In the meantime, commit is added to confirm transaction processing.

Ii. Data Definition (DDL)

1. Create (create a table, index, view, synonym, process, function, database link, etc)

Common Oracle field types include:
Char fixed-length string
Varchar2 variable-length string
Number (m, n) numeric type M is the total length of digits, n is the length of decimal places
Date type

When creating a table, you need to put a small field that is not empty in front of the field that may be empty in the back

You can use a Chinese field name when creating a table, but it is best to use an English field name.

When creating a table, you can add a default value to the field, for example, default sysdate.
In this way, the operation time can be obtained every time you insert or modify this field without any program operation.

When creating a table, you can add constraints to fields.
For example, duplicate unique is not allowed, and the key is primary key.

2. Alter (change tables, indexes, views, etc)

Change table name
Alter table table name 1 to table name 2;

Add a field to the end of the table.
Alter table table name add field Name field name description;

Modify the definition description of fields in the table
Alter table table name Modify Field Name field name description;

Add constraints to fields in the table
Alter table table name Add constraint name primary key (field name );
Alter table table name Add constraint name unique (field name );

Place the table in or out the memory area of the database
Alter table table name cache;
Alter table table name nocache;

3. Drop (Delete tables, indexes, views, synonyms, processes, functions, database links, etc)

Delete a table and all its constraints
Drop table name cascade constraints;

4. truncate (clear all records in the table and keep the table structure)

Truncate table name;

Iii. Select

Select field name 1, field name 2 ,...... From table name 1, [Table name 2,...] Where condition;

Field names can be imported into functions.
For example, count (*), min (field name), max (field name), AVG (field name), distinct (field name ),
To_char (Date Field name, 'yyyy-MM-DD hh24: MI: ss ')

Nvl (expr1, expr2) Function
Explanation:
If expr1 = NULL
Return expr2
Else
Return expr1

Decode (AA, V1, R1, V2, R2....) Function
Explanation:
If AA = V1 then return r1
If AA = v2 then return r2
..... Else
Return null

Lpad (char1, N, char2) Functions
Explanation:
Character char1 is displayed based on the specified number of digits n. The reserved number of digits is replaced by the reserved number on the left using the char2 string.

Arithmetic Operations can be performed between Field Names
Example: (field name 1 * field name 1)/3

The query statement can be nested.
Example: select ...... From
(Select ...... From table name 1, [Table name 2,...] Where condition) Where condition 2;

The results of two query statements can be set.
Example: Union (remove duplicate records), Union all (do not remove duplicate records), difference set minus, intersection intersect

Group Query
Select field name 1, field name 2 ,...... From table name 1, [Table name 2,...] Group by field name 1
[Having condition];

Query connections between two or more tables

Select field name 1, field name 2 ,...... From table name 1, [Table name 2,...] Where
Table Name 1. Field name = table name 2. Field name [and…] ;

Select field name 1, field name 2 ,...... From table name 1, [Table name 2,...] Where
Table Name 1. Field name = table name 2. Field name (+) [and…] ;

The position of a field with a (+) number is automatically null.

Sort the query result set. The default sorting is ASC in ascending order and desc in descending order.

Select field name 1, field name 2 ,...... From table name 1, [Table name 2,...]
Order by field name 1, field name 2 DESC;

Fuzzy string comparison

Instr (field name, 'string')> 0
Field name like 'string % '[' % string % ']

Each table has an implicit field rowid, which indicates the uniqueness of the record.

4. Common Data Objects (schema) in Oracle)

1. Index)

Create Index name on table name (Field 1, [Field 2,…] );
Alter Index name rebuild;

It is recommended that a table have no more than three indexes (except for a special large table). It is recommended that you use a single-field index to analyze the execution of SQL statements,
You can also create a multi-field composite index and a function-based index.

Oracle8.1.7 the maximum length of a string that can be indexed is 1578 bytes.
The maximum length of an oracle8.0.6 string that can be indexed is 758 bytes.

2. View)

Create view name as select .... From .....;
Alter view name compile;

A view is only an SQL query statement that simplifies the complex relationships between tables.

3. synonmy)
Create synonym name for table name;
Create synonym name for table name @ Database Link name;

4. Database Link)
Create database link database connection name connect to user name identified by password using 'database connection string ';

You can use net8 easy config for database connection strings or directly modify the definition in tnsnames. ora.

When the database parameter global_name = true, the Database Link name must be the same as the remote database name.

You can use the following command to check the global name of the database:
Select * From global_name;

Query tables in a remote database
Select ...... From table name @ Database Link name;

V. permission management (DCL) Statements

1. Grant Permissions
Common system permission sets include the following:
Connect (basic connection), Resource (Program Development), DBA (Database Management)
Common Data Objects have the following permissions:
All on Data Object Name, select on Data Object Name, update on Data Object Name,
Delete on Data Object Name, insert on Data Object Name, alter on Data Object Name

Grant connect, resource to user name;
Grant select on table name to user name;
Grant select, insert, delete on table name to username 1, username 2;

2. revoke permissions from revoke

Revoke connect, resource from username;
Revoke select on table name from user name;
Revoke select, insert, delete on table name from username 1, username 2;

Error 63rd in database query:
Select orgaddr, destaddr from sm_histable0116 where error_code = '63 ';

Query the maximum number of submitter and outgoing mails in the database: Select msisdn, TCOs, ocos from ms_usertable;

Query database errorsCodeTotal:
Select error_code, count (*) from sm_histable0513 group by error_code order
By error_code;

Query the statement statistical types in the report database.
Select sum (successcount) from tbl_middlemt0411 where servicetype2 = 111
Select sum (successcount), servicetype from tbl_middlemt0411 group by servicetype

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.