Oracle database common command set
1. User
View the relationship between users and the default tablespace
SELECT USERNAME, DEFAULT_TABLESPACE FROM DBA_USER;
View the default tablespace for the current user
select username,default_tablespace from user_users;
View the permissions of the current user
SELECT * FROM SESSION_PRIVS;
View all users
SELECT * FROM DBA_USER;
SELECT * FROM ALL_USER;
View user system permissions
SELECT * FROM DBA_SYS_PRIVS;
SELECT * FROM ALL_SYS_PRIVS;
View the system permissions of the current user
SELECT * FROM USER_SYS_PRIVS;
View User Object Permissions
SELECT * FROM DBA_TAB_PRIVS;
SELECT * FROM ALL_TAB_PRIVS;
View the table-level permissions of the current user
SELECT * FROM USER_TAB_PRIVS;
View all roles
SELECT * FROM DBA_ROLES:
View the roles a user has
SELECT * FROM DBA_ROLE_PRIVS;
View the current user's role
SELECT * FROM USER_ROLE_PRIVS;
delete users
DROP USER xx CASCADE;
View the size of the space occupied by a table
SELECT SEGMENT_NAME, BYTES FROM USER_SEGMENT WHERE SEGMENT_NAME='xxx'
View the size of a tablespace being used
SELECT SUM(BYTES) FROM USER_SEGMENT WHERE TABLESPACE_NAME='yyy';
View all users' tables
SELECT TABLE_NAME FROM ALL_TABLES;
Current user: USER_TABLES;
2. Table
View all tables under a user
SELECT * FROM USER_TABLES;
View tables whose names contain log characters
SELECT OBJECT_NAME,OBJECT_ID FROM USER_OBJECTS WHERE INSTR(OBJECT_NAME,'log')>0;
View the creation time of a table
SELECT OBJECT_NAME,CREATED FROM USER_OBJECTS WHERE OBJECT_NAME=UPPER('&TABLE_NAME');
View the size of a table
SELECT SUM(BYTES)/(1024*1024) AS "SIZE(M)" FROM USER_SEGMENTS WHERE SEGMENT_NAME=UPPER('&TABLE_NAME');
View the table placed in the memory area of ORACLE
select table_name,cache from user_tables where instr(cache,'Y')>0;
delete a table
TRUNCATE TABLE xxx;
optimize table
ANALYZE TABLE xxx COMPUTE STATISTICS FOR ALL INDEXES;
ANALYZE TABLE xxx COMPUTE STATISTICS;
ANALYZE TABLE xxx COMPUTE STATISTICS FOR TABLE FOR ALL INDEXES FOR ALL COLUMNS;
Delete analytics data
ANALYZE TABLE xxx DELETE STATISTICS;
※The TRUNCATE command does not update analysis data.
3. Index
View index counts and categories
SELECT INDEX_NAME,INDEX_TYPE,TABLE_NAME FROM USER_INDEXES ORDER BY TABLE_NAME;
View indexed fields
SELECT * FROM USER_IND_COLUMNS WHERE INDEX_NAME=UPPER('&INDEX_NAME');
Check the size of the index
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
SELECT * FROM USER_SEQUENCES;
5. View
View the name of the view
SELECT VIEW_NAME FROM USER_VIEWS;
View the select statement that creates the view
SET VIEW_NAME,TEXT_LENGTH FROM USER_VIEWS;
set long 2000; Description: You can set the size of set long according to the text_length value of the view
SELECT TEXT FROM USER_VIEWS WHERE VIEW_NAME=UPPER('&VIEW_NAME');
6. Synonyms
View synonym names
SELECT * FROM USER_SYNONYMS;
7. Constraints
View the constraints of a table
SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE,SEARCH_CONDITION, R_CONSTRAINT_NAME
FROM USER_CONSTRAINTS WHERE TABLE_NAME = UPPER('&TABLE_NAME');
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. Stored functions and procedures
View the status of functions and procedures
SELECT OBJECT_NAME,STATUS FROM USER_OBJECTS WHERE OBJECT_TYPE='FUNCTION';
SELECT OBJECT_NAME,STATUS FROM USER_OBJECTS WHERE OBJECT_TYPE='PROCEDURE';
View source code for functions and procedures
SELECT TEXT FROM ALL_SOURCE WHERE OWNER=USER AND NAME=UPPER('&PLSQL_NAME');
3. View the SQL of the database
1. View the name and size of the tablespace
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 physical file in the tablespace
SELECT TABLESPACE_NAME, FILE_ID, FILE_NAME,
ROUND(BYTES/(1024*1024),0) TOTAL_SPACE
FROM DBA_DATA_FILES
ORDER BY TABLESPACE_NAME;
3. View the name and size of the rollback segment
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 the control file
select name from v$controlfile;
5. View log files
select member from v$logfile;
6. Check the 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 library objects
select owner, object_type, status, count(*) count# from all_objects group by owner, object_type, status;
8. Check the version of the database
Select version FROM Product_component_version
Where SUBSTR(PRODUCT,1,6)='Oracle';
9. View the creation date and filing method of the database
Select Created, Log_Mode, Log_Mode From V$Database;
Four, ORACLE user connection management
Use the system administrator to see how many users are connected to the current database:
select username,sid,serial# from v$session;
If you want to stop a connection use
alter system kill session 'sid,serial#';
If this command does not work, find the number of UNIX processes
select pro.spid from v$session ses,v$process pro where ses.sid=21 and ses.paddr=pro.addr;
Description: 21 is the sid number of a connection
Then use the kill command to kill the process ID.
a, table creation, modification, deletion
The command format for creating a table is as follows:
create table table name (list of column descriptions);
The command to add a new column to the base table is as follows:
ALTER TABLE table name ADD (column description list)
Example: Add a column Age to the test table to store the age
alter table test
add (Age number(3));
The command to modify the base table column definition is as follows:
ALTER TABLE table name
MODIFY (column name data type)
Example: Lengthen the width of the Count column in the test table to 10 characters
alter atble test
modify (County char(10));
b. The format of the statement to delete a table is as follows:
DORP TABLE table name;
Example: table deletion will delete both the data of the table and the definition of the table
drop table test
c. Create and delete tablespaces
Seven, ORACLE commonly used SQL syntax and data objects
1. Data Control Statement (DML) part
1. INSERT (a statement to insert records into a data table)
INSERT INTO tablename(fieldname1, fieldname2, ...) VALUES (value1, value2, ...);
INSERT INTO table name (field name 1, field name 2, ...) SELECT (field name 1, field name 2, ...) FROM another table name;
Field values of type string must be enclosed in single quotes, for example: 'GOOD DAY'
If the field value contains a single quote ' and needs to be converted into a string, we replace it with two single quotes ''.
If the field value of the string type exceeds the defined length, an error will occur, and it is best to check the length before inserting.
The field value of the date field can use the current database system time SYSDATE, accurate to seconds
Or convert a string into a date function TO_DATE('2001-08-01','YYYY-MM-DD')
TO_DATE() has many other date formats, see ORACLE DOC.
Year-Month-Day Hour:Minute:Second format YYYY-MM-DD HH24:MI:SS
The maximum operable string length during INSERT is less than or equal to 4000 single bytes. If you want to insert a longer string, please consider using the CLOB type for the field.
The method borrows the DBMS_LOB package that comes with ORACLE.
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-incrementing serial number NUMBER(6), the maximum value is 999999
The INSERT statement inserts the value of this field: the name of the serial number.NEXTVAL
2. DELETE (delete the statement recorded in the data table)
DELETE FROM table name WHERE condition;
Note: Deleting records does not free up the occupied data block table space in ORACLE. It only marks those deleted data blocks as unused.
If you really want to delete all records in a large table, you can use the TRUNCATE command, which can release the occupied data block table space
TRUNCATE TABLE tablename;
This operation cannot be rolled back.
3.UPDATE (modify the statement 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 or defined, the original record content will be cleared to NULL, and it is best to perform non-null check before modification;
If the value N exceeds the defined length, an error will occur, it is best to perform a length check before inserting..
Precautions:
A. The above SQL statements add row-level locks to the tables,
After the confirmation is completed, the command COMMIT for the end of the transaction must be added to take effect.
Otherwise the changes are not necessarily written to the database.
If you want to undo these operations, you can use the command ROLLBACK to restore.
B. Before running INSERT, DELETE and UPDATE statements, it is best to estimate the record range of possible operations,
It should be limited to a small (10,000 records) range. Otherwise, ORACLE uses a large rollback segment to process this transaction.
The program response is slow or even lost. If there are more than 100,000 records of these operations, these SQL statements can be completed in stages.
In the meantime, add COMMIT to confirm transaction processing.
2. Data Definition (DDL) Section
1.CREATE (create tables, indexes, views, synonyms, procedures, functions, database links, etc.)
ORACLE commonly used field types are
CHAR fixed-length string
VARCHAR2 variable length string
NUMBER(M,N) The numeric type M is the total length of digits, and N is the length of the decimal
DATE date type
When creating a table, put the smaller non-empty fields in the front, and put the fields that may be empty in the back
You can use Chinese field names when creating tables, but it is better to use English field names
When creating a table, you can add default values to fields, such as DEFAULT SYSDATE
In this way, every time you insert and modify, you can get the action time without program manipulation of this field.
You can add constraints to fields when creating a table
For example, repeating UNIQUE is not allowed, the keyword PRIMARY KEY
2.ALTER (alter tables, indexes, views, etc.)
change table name
ALTER TABLE tablename1 TO tablename2;
Add a field to the back of the table
ALTER TABLE table name ADD field name field name description;
Modify the definition description of the fields in the table
ALTER TABLE table name MODIFY field name field name description;
Add constraints to the fields in the table
ALTER TABLE table name ADD CONSTRAINT constraint name PRIMARY KEY (field name);
ALTER TABLE table name ADD CONSTRAINT constraint name UNIQUE (field name);
Put the table in or out of the memory area of the database
ALTER TABLE table name CACHE;
ALTER TABLE 表名 NOCACHE;
3.DROP (drop table, index, view, synonym, procedure, function, database link, etc.)
drop the table and all its constraints
DROP TABLE 表名 CASCADE CONSTRAINTS;
4.TRUNCATE (empty all records in the table, keep the structure of the table)
TRUNCATE tablename;
3. Query statement (SELECT) part
SELECT field name 1, field name 2, ... FROM table name 1, [table name 2, ...] WHERE condition;
Field names can be brought 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
explain:
IF EXPR1=NULL
RETURN EXPR2
ELSE
RETURN EXPR1
DECODE(AA, V1, R1, V2, R2....) function
explain:
IF AA=V1 THEN RETURN R1
IF AA=V2 THEN RETURN R2
..…
ELSE
RETURN NULL
LPAD(char1,n,char2) function
explain:
The character char1 is displayed according to the specified number of digits n, and the insufficient digits are replaced by the char2 string to replace the empty space on the left
Arithmetic operations can be performed between field names
For example: (fieldname1*fieldname1)/3
Query statements can be nested
Example: SELECT ... FROM
(SELECT ... FROM table name 1, [table name 2, ...] WHERE condition) WHERE condition 2;
The results of the two query statements can be used for set operations
For example: union UNION (remove duplicate records), union UNION ALL (do not remove duplicate records), difference 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] ;
Join query between more than two 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 ...] ;
Fields with a (+) sign automatically fill in empty values
The sorting operation of 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;
A method for fuzzy string comparison
INSTR(field name, 'string')>0
Field name LIKE 'string%' ['%string%']
Each table has an implicit field ROWID, which marks the uniqueness of the record.
Four. Commonly used data objects in ORACLE (SCHEMA)
1. Index (INDEX)
CREATE INDEX index_name ON table_name(field1, [field2, ...] );
ALTER INDEX index name REBUILD;
The index of a table should not exceed three (except for special large tables), it is best to use a single field index, combined with the analysis and execution of SQL statements,
You can also build multi-field composite indexes and function-based indexes
The maximum length of the ORACLE8.1.7 string that can be indexed is 1578 single bytes
The maximum length of the ORACLE8.0.6 string that can be indexed is 758 single bytes
2. View (VIEW)
CREATE VIEW view name AS SELECT …. FROM …..;
ALTER VIEW view name COMPILE;
A view is just an SQL query statement that simplifies complex relationships between tables.
3. Synonyms (SYNONMY)
CREATE SYNONYM synonym name FOR table name;
CREATE SYNONYM synonym name FOR table name@database link name;
4. DATABASE LINK
CREATE DATABASE LINK database link name CONNECT TO user name IDENTIFIED BY password USING 'database connection string';
The database connection string can be defined in NET8 EASY CONFIG or directly modified in TNSNAMES.ORA.
When the database parameter global_name=true, the database link name is required to be the same as the remote database name
The database global name can be found out with the following command
SELECT * FROM GLOBAL_NAME;
Query the table in the remote database
SELECT ...... FROM table name@database link name;
5. Rights Management (DCL) Statement
1. GRANT gives permission
There are three commonly used system permission sets:
CONNECT (basic connection), RESOURCE (program development), DBA (database management)
There are five commonly used data object 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 username;
GRANT SELECT ON table name TO user name;
GRANT SELECT, INSERT, DELETE ON table name TO user name 1, user name 2;
2. REVOKE recycling permission
REVOKE CONNECT, RESOURCE FROM username;
REVOKE SELECT ON table name FROM user name;
REVOKE SELECT, INSERT, DELETE ON table name FROM user name 1, user name 2;
Error number 63 in the query database:
select orgaddr,destaddr from sm_histable0116 where error_code='63';
Query the maximum number of submissions and releases of account-opening users in the database: select MSISDN,TCOS,OCOS from ms_usertable;
Query the database for the sum of various error codes:
select error_code,count(*) from sm_histable0513 group by error_code order
by error_code;
Query the type of CDR statistics in the query report database.
select sum(Successcount) from tbl_MiddleMt0411 where ServiceType2=111
select sum(successcount),servicetype from tbl_middlemt0411 group by servicetype