Thursday, July 18, 2024

Coding tutorials - Sql *

 

Coding tutorials - Sql*



SQL> show user

SQL> connect peter/chen@waketech

SQL> show user

SQL> select * from tab;

SQL> disconnect

SQL> exit

=========

SQL> SHOW USER

SQL> SELECT * FROM emp;

SQL> SELECT * FROM dept;

SQL> SELECT * FROM salgrade;

SQL> SET LINESIZE 150

SQL> SET PAGESIZE 100

SQL> SHOW LINESIZE

SQL> SHOW PAGESIZE

SQL> SELECT * FROM emp;

SQL> LIST

Or

SQL> L

SQL> SELECT * FROM dept;

SQL> SELECT * FROM salgrade;

SQL> ED

=========

SQL> CREATE TABLE test(

 empno NUMBER,

 sal NUMBER);

SQL> INSERT INTO test VALUES(1000, 5000.333);

SQL> INSERT INTO test VALUES(1000, .333);

SQL> INSERT INTO test VALUES(1000, 500.333);

SQL> SELECT *

 FROM test;

=========

1. Data Definition Language (DDL)
o DDL changes the structure of the table lise creating a tables deleting a tables
altering a tables etc.
o All the command of DDL are auto-committed that means it permanently save
all the changes in the database.

Here are some commands that come under DDL:
o CREATE
o ALTER
o DROP
o TRUNCATE
a. CREATE It is used to create a new table in the database.
Syntax:
CREATE TABLE TABLE_NAME
(
 COLUMN_NAME1 DATATYPES(size)s
 COLUMN_NAME2 DATATYPES(size)s
 --------------
 COLUMN_NAMEN DATATYPES(size)s
);
Example:
CREATE TABLE EMP
(
 EMPNo VARCHAR2(20)s
 EName VARCHAR2(20)s
 Job VARCHAR2(20)s
 DOB DATE
);

b. DROP : This statement is used to drop an existing database. When you use this statement,
complete information present in the database will be lost.
Syntax
 DROP DATABASE DatabaseName;
Example
 DROP DATABASE Employee;
The ‘DROP TABLE’ Statement
This statement is used to drop an existing table. When you use this statement, complete
information present in the table will be lost.
Syntax
 DROP TABLE TableName;
Example
 DROP Table Emp;
c. ALTER
This command is used to delete, modify or add constraints or columns in an existing
table.
The ‘ALTER TABLE’ Statement
This statement is used to add, delete, modify columns in an existing table.
The ‘ALTER TABLE’ Statement with ADD/DROP COLUMN

The ‘ALTER TABLE’ Statement with ADD/DROP COLUMN
You can use the ALTER TABLE statement with ADD/DROP Column command
according to your need. If you wish to add a column, then you will use the ADD
command, and if you wish to delete a column, then you will use the DROP COLUMN
command.
Syntax
 ALTER TABLE TableName ADD ColumnName Datatype;
 ALTER TABLE TableName DROP COLUMN ColumnName;
Example
--ADD Column MobNo:
 ALTER TABLE Emp ADD MobNo Number(10);
--DROP Column MobNo:
ALTER TABLE Emp DROP COLUMN MobNo ;
The ‘ALTER TABLE’ Statement with ALTER/MODIFY COLUMN
This statement is used to change the datatype of an existing column in a table.
Syntax
 ALTER TABLE TableName ADD COLUMN ColumnName Datatype;
Example
--Add a column DOB and change the data type to Date.
 ALTER TABLE Emp ADD DOB date;
d. TRUNCATE
This command is used to delete the information present in the table but does not delete
the table. So, once you use this command, your information will be lost, but not the
table.
Syntax:
 TRUNCATE TABLE table_name;
Example:
 TRUNCATE TABLE EMPLOYEE;

2. Data Manipulation Language
o DML commands are used to modify the database. It is responsible for all form
of changes in the database.
o The command of DML is not auto-committed that means it can't permanently
save all the changes in the database. They can be rollbacs.
Here are some commands that come under DML:
o INSERT
o UPDATE
o DELETE
a. INSERT: The INSERT statement is a SQL query. It is used to insert data
into the row of a table.

Syntax:
 INSERT INTO TABLE_NAME
 (col1s col2s col3s.... col N)
 VALUES (value1s value2s value3s .... valueN);
Or
 INSERT INTO TABLE_NAME
 VALUES (value1s value2s value3s .... valueN);
For example:
 INSERT INTO EMP(ENamesJob) VALUES ("SCOTT"s "MANAGER");
b. UPDATE: This command is used to update or modify the value of a
column in the table.
Syntax:
UPDATE table_name SET column1= values column2= values
columnN = value WHERE CONDITION;
For example:
UPDATE Emp SET Ename = 'SMITH' WHERE EmpNo = '1003';
c. DELETE: It is used to remove one or more row from a table.

3. Data Control Language
DCL commands are used to grant and tase bacs authority from any database
user.
Here are some commands that come under DCL:
o Grant
o Revose
a. Grant: It is used to give user access privileges to a database.
Example
 GRANT SELECTs UPDATE ON MY_TABLE TO SOME_USERs ANOTHER_USER;
b. Revoke: It is used to tase bacs permissions from the user.
Example
 REVOKE SELECTs UPDATE ON MY_TABLE FROM USER1s USER2;
4. Transaction Control Language
TCL commands can only use with DML commands lise INSERTs DELETE and
UPDATE only.
These operations are automatically committed in the database that's why
they cannot be used while creating tables or dropping them.
Here are some commands that come under TCL:

o COMMIT
o ROLLBACK
o SAVEPOINT
a. Commit: Commit command is used to save all the transactions to the
database.
Syntax:
 COMMIT;
Example:
 DELETE FROM CUSTOMERS WHERE AGE = 25;
 COMMIT;
b. Rollback: Rollbacs command is used to undo transactions that have not
already been saved to the database.

Syntax:
 ROLLBACK;
Example:
 DELETE FROM CUSTOMERS WHERE AGE = 25;
 ROLLBACK;
c. SAVEPOINT: It is used to roll the transaction bacs to a certain point
without rolling bacs the entire transaction.
Syntax:
 SAVEPOINT SAVEPOINT_NAME;
5. Data Query Language
DQL is used to fetch the data from the database.
SELECT
This statement is used to select data from a database and the data returned is stored in
a result table, called the result-set.

Syntax
SELECT Column1, Column2, ...ColumN FROM TableName;
--(*) is used to select all from the table
 SELECT * FROM table_name;
-- To select the number of records to return use:
 SELECT TOP 3 * FROM TableName;
Apart from just using the SELECT keyword individually, you can use the following
keywords with the SELECT statement:
o
o DISTINCT
o ORDER BY
o GROUP BY
o HAVING Clause
o INTO
The ‘SELECT DISTINCT’ Statement
This statement is used to return only different values.
Syntax
SELECT DISTINCT Column1, Column2, ...ColumnN FROM TableName;
SELECT DISTINCT MobNo FROM Emp;
Example
The ‘ORDER BY’ Statement
The ‘ORDER BY’ statement is used to sort the required results in ascending or
descending order. The results are sorted in ascending order by default. Yet, if you wish
to get the required results in descending order, you have to use the DESC keyword.
Syntax
SELECT Column1, Column2, ...ColumnN FROM TableName
ORDER BY Column1, Column2, ... ASC|DESC;
Example
Select all employees from the 'Emp’ table sorted by EmpNo:
 SELECT * FROM Emp ORDER BY EmpNo;
-- Select all employees from the 'Emp table sorted by EmpNo in Descending order:
 SELECT * FROM Employee_Info ORDER BY EmpNo DESC;

===================

select distinct art.account_num,ch.billed_to_dat,ch.prev_bill_to_dat,ch.product_seq,ch.charge_type,ch.end_dat,(bm.balance_out_mny)/1000,bm.actual_bill_dtm,ast.account_status,art.ssa_code
from billsummary bm,billsummary bm1,custproductcharge ch,accountstatus ast,accountattributes art,(select count(*),bst.account_num account_num
from billsummary bst,accountstatus ast
where bst.account_num=ast.account_num
and bst.invoice_num like '1%'
and ast.account_status='TX'
group by bst.account_num
having count(*)=1
) temp1
where art.account_num=bm.account_num
and art.account_num=ch.customer_ref
and art.account_num=ast.account_num
and art.account_num=temp1.account_num
and bm1.account_num=bm.account_num
and bm.bill_seq in (select max(bst.bill_seq) from billsummary bst where bst.account_num=bm.account_num
group by bst.account_num)
and bm.bill_type_id='4'
and ast.account_status='TX'
and bm.cancelled_reason_txt is null
and bm1.bill_seq=bm.bill_seq-1
and ch.end_dat<='01-nov-2009'
and ch.product_seq='2'
and ch.charge_type='2'
and (ch.prev_bill_to_dat is null or ch.prev_bill_to_dat<bm1.bill_dtm-1)
and bm.balance_out_mny>0
and bm.invoice_num like '1%'
 
 select customer_ref,tariff_name from oper_rem.bbg_all_ssa
 where customer_ref in (select customer_ref from oper_rem.bbg_all_ssa  having count(customer_ref)>1
 group by customer_ref)-----385825 ----394352
 
 select account_num,bill_dtm,invoice_num from billsummary where invoice_num like '1%' and bill_dtm<'01-jan-2005'
 
 
select bST.account_num,bill_dtm,bill_type_id,bill_version,bill_status,invoice_net_mny/1000 invoice_net,invoice_tax_mny/1000 invoice_tax
from billsummary bst,accountstatus ast,accountattributes aa
where bst.account_num=ast.account_num
and bst.account_num=aa.account_num
and bst.invoice_num like '1%'
and ast.account_status='TX'
and TRUNC(ACTUAL_bill_dtm)='03-MAR-2011'
AND BILL_TYPE_ID='4'
and ssa_code='DIA'


==================
select ssa_code,a.account_num,aa.legacy_system_account_num,a.adjustment_dat, trunc(a.approved_dtm) approved_dtm, 
at.adjustment_type_desc,adjustment_net_mny/1000,'CREDIT', trunc(credit_adj_billed_to_dtm) credit_adj_billed_to_dtm  
 from adjustment a, accountattributes aa,adjustmenttype at,account ac
where a.bill_seq is null
and ac.account_num=aa.account_num
and a.account_num=aa.account_num
and a.adjustment_type_id=at.adjustment_type_id
and a.receivable_class_id=at.receivable_class_id
and trunc(a.approved_dtm)<trunc(credit_ADJ_BILLED_TO_DTM)
and adjustment_dat>'01-jan-2010'
and a.adjustment_status=3
and adjustment_net_mny>0
AND A.ACCOUNT_NUM IN (select distinct account_num from billsummary where event_seq is not null)
/*and aa.account_num='1003822488'*/

select ssa_code,a.account_num,aa.legacy_system_account_num,a.adjustment_dat, trunc(a.approved_dtm) approved_dtm, 
at.adjustment_type_desc,adjustment_net_mny/1000,'DEBIT', trunc(debit_adj_billed_to_dtm) debit_adj_billed_to_dtm   
from adjustment a, accountattributes aa,adjustmenttype at,account ac
where a.bill_seq is null
and ac.account_num=aa.account_num
and a.account_num=aa.account_num
and a.adjustment_type_id=at.adjustment_type_id
and a.receivable_class_id=at.receivable_class_id
and trunc(a.approved_dtm)<trunc(DEBIT_ADJ_BILLED_TO_DTM)
and adjustment_dat>'01-jan-2010'
and a.adjustment_status=3
and adjustment_net_mny<0
AND A.ACCOUNT_NUM IN (select distinct account_num from billsummary where event_seq is not null)
/*and aa.account_num='1003822488'*/



==============
select SSA_CODE,substr(TRUNC(bs.ACTUAL_bill_dtm),4,8) MONTH,BPC.receivable_class_id CLASS_ID,substr(receivable_class_name,1,9) CLASS_NAME,BPC.PRODUCT_ID,P.PRODUCT_NAME,
bpc.tariff_id TARIFF_ID,tariff_name TARIFF_NAME,
 count(distinct(BPC.account_num)) NO_OF_ACCOUNTS, sum(bpc.charge_cost_mny/1000) ABF
from billproductcharge bpc,tariff t, receivableclass rc,cataloguechange cc,billsummary bs,accountattributes aa,PRODUCT P
where bpc.account_num=bs.account_num
and  bpc.account_num=aa.account_num
and bpc.charge_seq=bs.event_seq
and bpc.tariff_id=t.tariff_id
AND BPC.PRODUCT_ID=P.PRODUCT_ID
and bpc.receivable_class_id=rc.receivable_class_id 
and t.catalogue_change_id=cc.catalogue_change_id
and cc.catalogue_status='3'
and trunc(ACTUAL_bill_dtm) between '01-JUN-2011' and '30-JUN-2011'  ---- CHANGE BILLING MONTH HERE
and bpc.bpc_status in ('1','2')
and bill_status in ('1','7','8')
and bpc.charge_cost_mny>0
and ssa_code='SRT' ----------CHANGE SSA CODE HERE
group by SSA_CODE,substr(TRUNC(bs.ACTUAL_bill_dtm),4,8),bpc.tariff_id,tariff_name,
BPC.receivable_class_id,receivable_class_name,BPC.PRODUCT_ID,P.PRODUCT_NAME
=========
---LL (INCL ISDN) REVENUE- CUSTOMER CATEGORY WISE

SELECT SSA_CODE,TRUNC(BS.BILL_DTM),AA.ACCOUNT_TYPE, AA.ACCOUNT_SUBTYPE,RECEIVABLE_CLASS_NAME ,
SUM( BR.INVOICE_MNY/1000) INV_MNY,COUNT(DISTINCT(BS.ACCOUNT_NUM))  NO_OF_ACCOUNTS
FROM BILLRECEIVABLE BR,BILLSUMMARY BS,RECEIVABLECLASS RC,ACCOUNTATTRIBUTES AA
WHERE BS.ACCOUNT_NUM=BR.ACCOUNT_NUM
AND BS.ACCOUNT_NUM=AA.ACCOUNT_NUM
AND BS.BILL_SEQ=BR.BILL_SEQ
AND BS.BILL_VERSION=BR.BILL_VERSION
AND BS.BILL_STATUS IN ('1','7','8')
AND BR.RECEIVABLE_CLASS_ID=RC.RECEIVABLE_CLASS_ID
AND BR.INVOICE_MNY/1000>0
AND BR.RECEIVABLE_CLASS_ID='1'  ----(INCLUDES BOTH PURE LL AND ISDN)
AND SSA_CODE='IND'  -----CHANGE SSA_CODE HERE
AND TRUNC(BS.ACTUAL_BILL_DTM)  IN ('05-SEP-2011','06-SEP-2011') ----CHANGE ACTUAL BILL DATE HERE
GROUP BY SSA_CODE,TRUNC(BS.BILL_DTM),AA.ACCOUNT_TYPE, AA.ACCOUNT_SUBTYPE,RECEIVABLE_CLASS_NAME



---BB REVENUE- CUSTOMER CATEGORY WISE

SELECT SSA_CODE,TRUNC(BS.BILL_DTM),AA.ACCOUNT_TYPE, AA.ACCOUNT_SUBTYPE,RECEIVABLE_CLASS_NAME ,
SUM( BR.INVOICE_MNY/1000) INV_MNY,COUNT(DISTINCT(BS.ACCOUNT_NUM)) NO_OF_ACCOUNTS
FROM BILLRECEIVABLE BR,BILLSUMMARY BS,RECEIVABLECLASS RC,ACCOUNTATTRIBUTES AA
WHERE BS.ACCOUNT_NUM=BR.ACCOUNT_NUM
AND BS.ACCOUNT_NUM=AA.ACCOUNT_NUM
AND BS.BILL_SEQ=BR.BILL_SEQ
AND BS.BILL_VERSION=BR.BILL_VERSION
AND BS.BILL_STATUS IN ('1','7','8')
AND BR.RECEIVABLE_CLASS_ID=RC.RECEIVABLE_CLASS_ID
AND BR.INVOICE_MNY/1000>0
AND BR.RECEIVABLE_CLASS_ID='2' 
AND SSA_CODE='IND'  -----CHANGE SSA_CODE HERE
AND TRUNC(BS.ACTUAL_BILL_DTM)  IN ('05-SEP-2011','06-SEP-2011')----CHANGE ACTUAL BILL DATE HERE
GROUP BY SSA_CODE,TRUNC(BS.BILL_DTM),AA.ACCOUNT_TYPE, AA.ACCOUNT_SUBTYPE,RECEIVABLE_CLASS_NAME


---- REVENUE CODE WISE ABF DETAILS 

SELECT SSA_CODE,SUBSTR( ACTUAL_BILL_DTM,4,8) BILLING_MONTH,substr(RC.REVENUE_CODE_NAME,1,6) REVENUE_CODE,RC.REVENUE_CODE_DESC,
 SUM(BD.REVENUE_MNY/1000) ABF, COUNT(DISTINCT(BS.ACCOUNT_NUM)) NO_OF_ACCOUNTS
FROM BILLDETAILS BD,BILLSUMMARY BS,ACCOUNTATTRIBUTES AA,REVENUECODE RC
WHERE BS.ACCOUNT_NUM=AA.ACCOUNT_NUM
AND BS.ACCOUNT_NUM=BD.ACCOUNT_NUM
AND BS.BILL_SEQ=BD.BILL_SEQ
AND BS.BILL_VERSION=BD.BILL_VERSION
AND BS.BILL_STATUS IN ('1','7','8')
AND BD.REVENUE_CODE_ID =rc.revenue_code_id 
AND AA.SSA_CODE='IND'   -----------SSA CODE
AND TRUNC(ACTUAL_BILL_DTM) in ('05-SEP-2011','06-SEP-2011')----CHANGE ACTUAL BILL DATE HERE
GROUP BY SSA_CODE,SUBSTR( ACTUAL_BILL_DTM,4,8),substr(RC.REVENUE_CODE_NAME,1,6) ,RC.REVENUE_CODE_DESC
---------------
========================
--------- CHECKING OF LATE PAYMENT FEE 


select distinct adj.account_num,adj.adjustment_seq,adj.adjustment_dat,adj.adjustment_txt,bm.bill_dtm,bm.payment_due_dat,(adj.adjustment_net_mny/1000) adj_mny,(bm.balance_out_mny/1000)bal_out_mny,(ap.account_payment_mny /1000) payment_mny,ap.account_payment_dat,ap.created_dtm,trunc(act.trans_billed_to_dtm)
from accountattributes art,adjustment adj,billsummary bm,accountpayment ap,account act  
where art.account_num=adj.account_num
and bm.account_num=art.account_num
and act.account_num=art.account_num
and ap.account_num=bm.account_num
and adj.adjustment_type_id='77'
and adj.adjustment_dat='31-may-2011'
/*and art.circle_code='GJ'*/
and bm.bill_seq=adj.bill_seq-1
and trunc(ap.account_payment_dat) between trunc(bm.actual_bill_dtm) and bm.payment_due_dat
and ap.account_payment_mny>=bm.balance_out_mny
and trunc(ap.created_dtm)=trunc(act.trans_billed_to_dtm)
/*and ap.created_dtm>bm.payment_due_dat*/
and adj.account_num in(select * from late_all)   ---CUSTOM TABLE
==============

---------OYT REBATE GIVEN TWICE FOR THE SAME MONTH - PROBLEM NOTICED ON 25.05.2011

-----AFFECTED ACCOUNTS

SELECT * FROM bsnl_deposit_interest WHERE  REBATE>0 HAVING COUNT(*)>1 
GROUP BY ACCOUNT_NUM,ORDER_ID ,TELEPHONE_NO,DEPOSIT_ID,SEQUENCE_ID,DEPOSIT_AMOUNT,
INTEREST_ON_DEPOSIT,REBATE,ACC_CHARGES,START_DT,END_DT,INTEREST_CALCULATION_DT,EXECUTION_STATUS,ACCOUNT_TYPE,REC_MD_DT  

-----AFFECTED SSAs
select ssa_code,count(*) from accountattributes where account_num in (
SELECT distinct account_num FROM bsnl_deposit_interest WHERE  REBATE>0 HAVING COUNT(*)>1 
GROUP BY ACCOUNT_NUM,ORDER_ID ,TELEPHONE_NO,DEPOSIT_ID,SEQUENCE_ID,DEPOSIT_AMOUNT,
INTEREST_ON_DEPOSIT,REBATE,ACC_CHARGES,START_DT,END_DT,INTEREST_CALCULATION_DT,EXECUTION_STATUS,ACCOUNT_TYPE,REC_MD_DT )
group by ssa_code


--------- account numbers whose OYT bal became 0 after updation and who may need to be given debits for over paid rebate

select account_num from bsnl_deposit_interest where  account_num in (
SELECT account_num FROM bsnl_deposit_interest WHERE  REBATE>0  HAVING COUNT(*)>1 
GROUP BY ACCOUNT_NUM,ORDER_ID ,TELEPHONE_NO,DEPOSIT_ID,SEQUENCE_ID,DEPOSIT_AMOUNT,
INTEREST_ON_DEPOSIT,REBATE,ACC_CHARGES,START_DT,END_DT,INTEREST_CALCULATION_DT,EXECUTION_STATUS,ACCOUNT_TYPE,REC_MD_DT)
and deposit_amount<=1
================

Oracle SQL (Structured Query Language) is a powerful database language used to manage and manipulate Oracle databases. Here are some key concepts and examples to help you get started:

 

### Basic SQL Operations

 

#### 1. **Creating a Table**

 

```sql

CREATE TABLE employees (

    employee_id NUMBER PRIMARY KEY,

    first_name VARCHAR2(50),

    last_name VARCHAR2(50),

    email VARCHAR2(100) UNIQUE,

    hire_date DATE,

    job_id NUMBER,

    salary NUMBER

);

```

 

#### 2. **Inserting Data**

 

```sql

INSERT INTO employees (employee_id, first_name, last_name, email, hire_date, job_id, salary)

VALUES (1, 'John', 'Doe', 'john.doe@example.com', TO_DATE('2023-01-15', 'YYYY-MM-DD'), 101, 60000);

```

 

#### 3. **Querying Data**

 

```sql

SELECT * FROM employees;

 

SELECT first_name, last_name, salary

FROM employees

WHERE salary > 50000;

```

 

#### 4. **Updating Data**

 

```sql

UPDATE employees

SET salary = 65000

WHERE employee_id = 1;

```

 

#### 5. **Deleting Data**

 

```sql

DELETE FROM employees

WHERE employee_id = 1;

```

 

### Advanced SQL Operations

 

#### 1. **Joining Tables**

 

Assuming you have another table called `departments`:

 

```sql

SELECT e.first_name, e.last_name, d.department_name

FROM employees e

JOIN departments d ON e.department_id = d.department_id;

```

 

#### 2. **Using Aggregate Functions**

 

```sql

SELECT department_id, AVG(salary) AS average_salary

FROM employees

GROUP BY department_id;

```

 

#### 3. **Subqueries**

 

```sql

SELECT first_name, last_name

FROM employees

WHERE salary > (SELECT AVG(salary) FROM employees);

```

 

#### 4. **Creating a View**

 

```sql

CREATE VIEW high_earners AS

SELECT first_name, last_name, salary

FROM employees

WHERE salary > 50000;

```

 

#### 5. **Using PL/SQL for Procedural Logic**

 

PL/SQL is Oracle's procedural extension for SQL. Here’s a simple example of a PL/SQL block:

 

```sql

DECLARE

    v_total_salary NUMBER;

BEGIN

    SELECT SUM(salary) INTO v_total_salary FROM employees;

    DBMS_OUTPUT.PUT_LINE('Total Salary: ' || v_total_salary);

END;

```

 

### Tips for Writing Efficient SQL in Oracle

 

1. **Use Indexes**: Indexes can significantly speed up queries. Make sure to index columns that are frequently used in WHERE clauses or JOIN conditions.

  

   ```sql

   CREATE INDEX idx_employee_last_name ON employees(last_name);

   ```

 

2. **Avoid Using `SELECT *`**: Specify the columns you need instead of using `SELECT *`.

 

3. **Use Bind Variables**: Bind variables can improve performance by reusing execution plans.

 

4. **Optimize Joins**: Use appropriate join types and conditions. Prefer inner joins over outer joins when possible.

 

5. **Analyze Execution Plans**: Use the `EXPLAIN PLAN` statement to understand how Oracle executes your query and identify potential bottlenecks.

 

   ```sql

   EXPLAIN PLAN FOR

   SELECT first_name, last_name FROM employees WHERE salary > 50000;

  

   SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);

   ```

 

Oracle SQL is a powerful tool for managing data, and mastering it can greatly enhance your ability to work with Oracle databases efficiently.

====

SQL*Plus is a command-line tool that provides an interface to interact with Oracle Database. It allows users to execute SQL, PL/SQL, and SQL*Plus commands. Here are some commonly used SQL*Plus commands and their functionalities:

 

### Starting SQL*Plus

 

```bash

sqlplus username/password@database

```

 

### SQL*Plus Commands

 

#### 1. **Connecting to a Database**

 

```sql

CONNECT username/password@database

```

 

#### 2. **Exiting SQL*Plus**

 

```sql

EXIT

```

 

#### 3. **Executing SQL Scripts**

 

```sql

START script_name.sql

@script_name.sql

```

 

#### 4. **Formatting Output**

 

- **Setting Column Widths:**

 

  ```sql

  COLUMN column_name FORMAT A30

  ```

 

- **Setting Page Size:**

 

  ```sql

  SET PAGESIZE 50

  ```

 

- **Setting Line Size:**

 

  ```sql

  SET LINESIZE 100

  ```

 

- **Suppressing Output:**

 

  ```sql

  SET FEEDBACK OFF

  ```

 

- **Displaying Column Names Only Once:**

 

  ```sql

  SET HEADING ON

  ```

 

#### 5. **Spooling Output to a File**

 

```sql

SPOOL output_file.txt

-- Your SQL commands

SPOOL OFF

```

 

#### 6. **Displaying the Current User**

 

```sql

SHOW USER

```

 

#### 7. **Describing Database Objects**

 

```sql

DESC table_name

```

 

#### 8. **Setting SQL*Plus Variables**

 

- **Defining Variables:**

 

  ```sql

  DEFINE variable_name = value

  ```

 

- **Using Variables:**

 

  ```sql

  SELECT &variable_name FROM dual;

  ```

 

- **Unsetting Variables:**

 

  ```sql

  UNDEFINE variable_name

  ```

 

#### 9. **Environment Settings**

 

- **Setting the SQL Prompt:**

 

  ```sql

  SET SQLPROMPT 'SQL> '

  ```

 

- **Enabling and Disabling Autocommit:**

 

  ```sql

  SET AUTOCOMMIT ON

  SET AUTOCOMMIT OFF

  ```

 

- **Setting Timing for Commands:**

 

  ```sql

  SET TIMING ON

  ```

 

#### 10. **Executing PL/SQL Blocks**

 

```sql

BEGIN

    DBMS_OUTPUT.PUT_LINE('Hello, World!');

END;

/

```

 

### Example Session

 

Here's an example of a typical SQL*Plus session:

 

```bash

$ sqlplus scott/tiger@orcl

 

SQL*Plus: Release 19.0.0.0.0 - Production on Wed Aug 9 10:34:56 2023

 

Connected to:

Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production

Version 19.3.0.0.0

 

SQL> SET LINESIZE 150

SQL> SET PAGESIZE 50

SQL> COLUMN last_name FORMAT A20

SQL> SPOOL employee_report.txt

SQL> SELECT employee_id, first_name, last_name, salary

  2  FROM employees

  3  WHERE salary > 50000

  4  ORDER BY last_name;

 

EMPLOYEE_ID FIRST_NAME           LAST_NAME               SALARY

----------- -------------------- -------------------- ----------

          1 John                 Doe                    60000

          2 Jane                 Smith                  70000

 

SQL> SPOOL OFF

SQL> EXIT

``` 

### Helpful Tips

 

1. **Use Scripts**: Store frequently used commands in scripts and execute them with the `@` or `START` command.

2. **Use Aliases**: Create aliases for frequently used SQL statements to save time.

3. **Customize Environment**: Use the SQL*Plus environment settings to customize your session for better readability and efficiency.

4. **Check Error Messages**: Always check for error messages after running commands to ensure they executed successfully.


 SQL*Plus is a powerful tool for database administrators and developers to interact with Oracle Database. Mastering its commands can greatly enhance your productivity and efficiency.






Small coding languages

  Yes, Hack is a programming language developed by Facebook (now Meta) as a dialect of PHP. It was designed to address some of the limitatio...