# Accessing sqlplus
C:\Users\Rauhaan> sqlplus
SQL>
Username system
Password password
# disconnect from database / optional
SQL> disc
# Show name of current user
SQL> show user
# Create user (DDL)
C## - Common User: Common users can connect to and access objects in both the root container (CDB) and
pluggable databases (PDBs) within a multitenant environment.
PDBADMIN - Pluggable Database Administrator: A user with administrative privileges specifically for managing a
pluggable database.
DBA - Database Administrator: Typically used to prefix users or roles with administrative privileges over the
entire database system.
SYS - System User: The SYS user is a powerful administrative user account automatically created with every
Oracle database installation. It has unrestricted access to the Oracle database.
SYSTEM - System User: The SYSTEM user is another administrative user account created with every Oracle
database installation. It is typically used for database administration tasks.
HR - Human Resources: Used to prefix users or roles associated with human resources-related data and
operations.
FINANCE - Finance: Used to prefix users or roles associated with financial data and operations.
SALES - Sales: Used to prefix users or roles associated with sales-related data and operations.
SQL> create user C##user1 identified by password;,
User created.
# Using Grant (DCL) to provide privileges to user
SQL> grant dba to C##user1;
Grant succeeded.
# we just made the user1 administrator
# Connect to new user
SQL> conn C##user1
Enter password:
Connected.
# Create table (DDL)
SQL> create table class(id number, name varchar2(50), sub varchar2(10));
Table created.
# Show table details (DDL)
SQL> desc or describe class
# Show Database name
SQL> SELECT NAME FROM v$database;
# Create table defining char limit (DDL)
SQL> create table sales(
id number,
name varchar(2),
cogs number,
dep varchar2(20),
contact char(10),
gender char(1));
Table created.
# Insert data into table
SQL> insert into sales values(23, 'Ip', 80000, 'mobile', 749859075, 'M');
# Alter Table to reset the char limit for name column
SQL> alter table sales modify name varchar(20);
Table altered.
# Insert data into table again, notice same trans recorded again
SQL> insert into sales values(23, 'Iphone', 80000, 'mobile', 749859075, 'M');
1 row created.
# Insert multiple rows in same table
SQL> INSERT all
into sales values(24, 'computer', 100000, 'computer', 6767398749, 'F')
into sales values(25, 'watch', 4000, 'electronics', 897654637, 'M')
into sales values(26, 'chair', 14000, 'chairs', 8976567898, 'F')
into sales values(27, 'computer', 60000, 'computer', 6767398239, 'M')
into sales values(28, 'I watch', 30000, 'electronics', 897454637, 'F')
into sales values(29, 'computer', 20000, 'computer', 8346567898, 'M')
select * from dual;
3 rows created.
# Insert into multiple table
SQL> create table sales2(cust_name varchar2(20), cust_id number);
SQL> insert all
into sales values(25, 'watch', 4000, 'electronics', 897654637, 'M')
into sales2 values('rauhaan', 45673)
select * from dual;
2 rows created.
# use Commit to make changes permanent
SQL> commit;
Commit complete
# How to rename column of a table
SQL> alter table sales rename column name to product;
# How to rename table
SQL> alter table sales rename to supermarket_sales;
Table altered.
# How to drop columns of table
SQL> alter table supermarket_sales drop column gender;
# Validate
SQL> desc supermarket_sales
# How to modify multiple columns of a table
SQL> alter table supermarket_sales modify (product varchar2(30), dep varchar2(30));
# Validate
SQL> desc supermarket_sales
# Add columns to a table
SQL> alter table supermarket_sales add profit number;
Table altered.
# Add multiple columns to a table
SQL> alter table supermarket_sales add (bcode char(3), city char(3));
Table altered.
# Validate
SQL> desc supermarket_sales
# See all tables created by user ( show tables)
SQL> SELECT table_name FROM user_tables;
# Drop table
SQL> drop table emp;
# Delete permanently , will not be possible to recover if used PURGE
SQL> DROP TABLE emp PURGE ;
# Create table from a table
SQL> create table new_table as (SELECT * from supermarket_sales);
Table created.
# Create table with selected column from a table
SQL> create table roduct_vs_cogs as (SELECT product, cogs from supermarket_sales);
Table created.
# Creating global temporary table
SQL> CREATE GLOBAL TEMPORARY TABLE stu
(id number,
name varchar2(50),
address varchar2(50)
);
# UPDATE data in the table
SQL> UPDATE supermarket_sales
SET Bcode = 1 ;
SQL> UPDATE supermarket_sales
SET City = 'PUN'
SQL> UPDATE supermarket_sales
SET City = 'MUM'
WHERE dep = 'electronics';
# Delete data in table
SQL> delete from supermarket_sales where product = 'iphone';
1 row deleted.
# Delete on multiple conditions
SQL> delete from supermarket_sales where product = 'watch' and cogs > 3000;
2 rows deleted.
# Truncate table
SQL> create table dup_sales as select * from supermarket_sales;
Table created.
SQL> truncate table dup_sales;
Table truncated.
# FROM Clause Example: (with one table)
SQL> select * from supermarket_sales;
# DISTINCT Clause Example
SQL> SELECT DISTINCT CITY FROM SUPERMARKET_SALES
# DISTINCT Example: (with multiple expressions)
SQL> SELECT DISTINCT DEP FROM SUPERMARKET_SALES WHERE CITY = 'pun';
# Order by Clause
SQL> select* from supermarket_sales order by profit;
# Order by Clause Sorting in descending order
SQL> select * from supermarket_sales order by name desc;
# GROUP BY
SQL> select dep, sum(cogs) as "Total sales" from supermarket_sales group by DEP;
# GROUP BY (With count function)
SQL> select gender, count(Gender) from supermarket_sales group by gender;
# GROUP BY and HAVING
Produts grouped by dep having cogs more than 50000
SQL> select dep, SUM(cogs) as "high product sales" from supermarket_sales
group by dep
having sum(cogs) > 50000;
Produts grouped by dep having cogs less than 20000
SQL> select dep, SUM(cogs) as "low product sales" from supermarket_sales
group by dep
having sum(cogs) < 20000;
SQL> select dep, count(*) as "no of sales" from supermarket_sales
where cogs > 10000
group by dep
having count(*) > = 2;
# Run script to create table and load data
SQL> @’load_samples.sql’
# Generate CSV reports from query using SPOOL
### colsep is the column separator (delimiter) used to separate the fields in the CSV file. For this example, a
comma is used. However, different separators can be used as well.
### headsep is required when the user wants to publish a header in the output file. In this example, this is set to
off as a header is not needed.
### pagesize is the parameter used to control the number of lines per page in the output. Since you are writing to
a file, set this number to 0.
### trimspool is set to on to remove trailing whitespace.
##### To execute the script, simply use the @ symbol followed by the file name:
##### @file_name
##### Your script should be executed and the .csv file created as expected.
set colsep ,
set headsep off
set pagesize 0
set trimspool on
spool C:\Users\Dell\Desktop\low_Sal_by_dep.csv
SELECT department_id,
MIN(salary) AS "Lowest salary"
FROM employees
GROUP BY department_id;
spool off
# to get lowest salary vs department
SELECT department_id,
MIN(salary) AS "Lowest salary"
FROM employees
GROUP BY department_id;
# to get highest salary vs department
SELECT department_id,
max(salary) AS "highest salary"
FROM employees
GROUP BY department_id;
# To get lowest salary vs department having min
SELECT department_id,
MIN(salary) AS "Lowest salary"
FROM employees
GROUP BY department_id
having min(salary) < 4000;
# To get lowest salary vs department having min
SELECT department_id,
max(salary) AS "highest salary"
FROM employees
GROUP BY department_id
having max(salary) >= 10000;
# Constrains
-----NOT NULL
CREATE TABLE Persons (
ID number NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
CREATE TABLE Persons (
ID number ,
LastName varchar(255) ,
FirstName varchar(255) ,
Age int
);
SQL> insert into Persons (LastName) values ('b');
insert into Persons (LastName) values ('b')
ERROR at line 1:
ORA-01400: cannot insert NULL into ("USER1"."PERSONS"."ID")
---UNIQUE
CREATE TABLE persons2 (
ID number NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
SQL> insert into Persons2 values (1,'r', 'b', 50);
1 row created.
SQL> insert into Persons2 values (1,'r', 'b', 50);
insert into Persons2 values (1,'r', 'b', 50)
*
ERROR at line 1:
ORA-00001: unique constraint (USER1.SYS_C007124) violated
---PRIMARY KEY
CREATE TABLE persons3 (
ID number PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
SQL> insert into Persons3 values (1,'r', 'b', 50);
1 row created.
SQL> insert into Persons3 values (1,'r', 'b', 50);
insert into Persons3 values (1,'r', 'b', 50)
ERROR at line 1:
ORA-00001: unique constraint (USER1.SYS_C007126) violated
---DEFAULT
CREATE TABLE persons4 (
ID int NOT NULL,
LastName varchar(20) NOT NULL,
FirstName varchar(20),
Age int,
City varchar(20) DEFAULT 'MUM'
);
SQL> insert into Persons4 (ID, LastName, FirstName, Age) values (1,'r','b',50);
2 ;
1 row created.
SQL> select * from persons4;
--Check
CREATE TABLE persons5 (
ID int NOT NULL,
LastName varchar(30) NOT NULL,
FirstName varchar(30),
Age int,
CHECK (Age>=20)
);
SQL> insert into Persons5 values(1,'r','b', 18);
insert into Persons5 values(1,'r','b', 18)
ERROR at line 1:
ORA-02290: check constraint (USER1.SYS_C007131) violated
Creating and dropping constrints
create table foo (id varchar(26) not null, name varchar(50) not null)
alter table foo add constraint pk_foo primary key (id)
alter table foo add constraint un_foo unique (name)
alter table foo drop constraint un_foo
alter table foo drop constraint pk_foo