You are on page 1of 41

SQL Statements

As of creating this document you don't know how to work with dates like grouping
them and sorting them...
TO_CHAR () , TO_DATE () , YEAR () , STR_TO_DATE () , DATEPART () and other DATE functions
in general need to be learnt...
Checkout Various SQL Server Functions and MySQL Server Functions here.
Creating Table

CREATE TABLE customers


( customer_id number(10) NOT NULL,
customer_name varchar2(50) NOT NULL,
city varchar2(50),
CONSTRAINT customers_pk PRIMARY KEY (customer_id)
);

Creating Table by copying all columns of another table

CREATE TABLE newcustomers AS (SELECT * FROM customers);

Creating Table by copying select columns of another table

CREATE TABLE newcustomers2 AS (SELECT customer_id, customer_name FROM customers);

We could use WHERE to filter out required Rows to be copied

CREATE TABLE newcustomers2 AS (SELECT customer_id, customer_name FROM customers WHERE cust
omer_id < 5000);

Creating a Table having all columns of Table2 but without any data

CREATE TABLE newcustomers AS (SELECT * FROM customers WHERE 1 = 2 /* We can use any False
Statement */);

SQL Statements 1
Consider that you have already created two tables "regularcustomers" and
"irregularcustomers".
The table "regularcustomers" has three columns rcustomer_id , rcustomer_name and
rc_city .

CREATE TABLE "regularcustomers"


(
"RCUSTOMER_ID" NUMBER(10,0) NOT NULL ENABLE,
"RCUSTOMER_NAME" VARCHAR2(50) NOT NULL ENABLE,
"RC_CITY" VARCHAR2(50)
)

The table "irregularcustomers" has three columns ircustomer_id , ircustomer_name and


irc_city .

CREATE TABLE "irregularcustomers"


(
"IRCUSTOMER_ID" NUMBER(10,0) NOT NULL ENABLE,
"IRCUSTOMER_NAME" VARCHAR2(50) NOT NULL ENABLE,
"IRC_CITY" VARCHAR2(50)
)

In the following example, we will create a table name "newcustomers3" form copying
columns from both tables.

CREATE TABLE newcustomers3


AS (SELECT regularcustomers.rcustomer_id, regularcustomers.rc_city, irregularcustomers.i
rcustomer_name
FROM regularcustomers, irregularcustomers);

We could also implement any conditions like customers common in both tables.

CREATE TABLE newcustomers3


AS (SELECT regularcustomers.rcustomer_id, regularcustomers.rc_city, irregularcustomers.i
rcustomer_name
FROM regularcustomers, irregularcustomers
WHERE regularcustomers.rcustomer_id = irregularcustomers.ircustomer_id
AND regularcustomers.rcustomer_id < 5000);

SQL Statements 2
Read about SELECT in ACE Textbook
UPDATE Statement

-- This example will update the supplier_name as "Kingfisher" where "supplier_id" is 2.


UPDATE suppliers
SET supplier_name = 'Kingfisher'
WHERE supplier_id = 2;

-- The following example specifies how to update multiple columns in a table.


-- In this example, two columns supplier_name and supplier_address is updated by a single
statement.

UPDATE suppliers
SET supplier_address = 'Agra',
supplier_name = 'Bata shoes'
WHERE supplier_id = 1;

-- Update Example: (By selecting records from another table)

UPDATE customers
SET name = (SELECT supplier_name
FROM suppliers
WHERE suppliers.supplier_name = customers.name)
WHERE age < 25;

-- the customers table is updated by fetching the data from "suppliers" table.

INSERT INTO Statement

-- (Inserting a single record using the Values keyword):

INSERT INTO table


(column1, column2, ... column_n )
VALUES
(expression1, expression2, ... expression_n );

-- (Inserting multiple records using a SELECT statement):

INSERT INTO table


(column1, column2, ... column_n )
SELECT expression1, expression2, ... expression_n
FROM source_table
WHERE conditions;

-- Using VALUES Keyword

INSERT INTO suppliers


(supplier_id, supplier_name)

SQL Statements 3
VALUES
(50, 'Flipkart');

This example specifies how to insert multiple records in one table. Here we insert three
rows into the "suppliers" table.

INSERT ALL
INTO suppliers (supplier_id, supplier_name) VALUES (20, 'Google')
INTO suppliers (supplier_id, supplier_name) VALUES (21, 'Microsoft')
INTO suppliers (supplier_id, supplier_name) VALUES (22, 'Apple')
SELECT FROM dual;

In the following example, we are going to insert records into the both "suppliers" and
"customers" tables.

INSERT ALL
INTO suppliers (supplier_id, supplier_name) VALUES (30, 'Google')
INTO suppliers (supplier_id, supplier_name) VALUES (31, 'Microsoft')
INTO customers (age, name, address) VALUES (29, 'Luca Warsi', 'New York')
SELECT * FROM dual;

BETWEEN is used to get the values from given range in select, insert, delete or update
statement. Using BETWEEN in the following example.

SELECT id, name, age FROM table1 WHERE age BETWEEN 20 AND 28

Using BETWEEN with NOT operator

SELECT id, name, age FROM table1 WHERE age NOT BETWEEN 20 AND 28

Using BETWEEN with INSERT statement

INSERT INTO Customers (CustomerName, City, Country) (SELECT SupplierName, City, Country FR
OM Suppliers WHERE s_num BETWEEN 100 AND 500)

Using BETWEEN with DELETE statement

SQL Statements 4
Delete FROM table1 WHERE id BETWEEN 79 AND 296

Using BETWEEN for Date Values

SELECT * FROM emp WHERE hiredate BETWEEN TO_DATE ('1981/04/02', 'yyyy/mm/dd') AND TO_DATE
('1981/06/09', 'yyyy/mm/dd')

TO_DATE Function

TO_DATE('2003/07/09', 'yyyy/mm/dd')

/* Result: date value of July 9, 2003 */

TO_DATE('070903', 'MMDDYY')

/* Result: date value of July 9, 2003 */

TO_DATE('20020315', 'yyyymmdd')
-- Result: date value of Mar 15, 2002

DELETE with One Condition

DELETE FROM customers WHERE name = 'Sohan';

DELETE with Multiple Conditions

DELETE FROM customers WHERE last_name = 'Maurya' AND customer_id > 2;

DELETE all Rows

DELETE FROM customers

Using ALTER - RENAME to rename table

ALTER TABLE customers RENAME TO retailers;

SQL Statements 5
Using ALTER - RENAME to rename Column

ALTER TABLE customers RENAME COLUMN customer_name to cname;

Using ALTER - MODIFY to modify single Column

ALTER TABLE customers MODIFY customer_name varchar2(100) NOT null;

Using ALTER - MODIFY to modify multiple Columns

ALTER TABLE customers MODIFY (customer_name varchar2(100) NOT null, city varchar2(100));

Using ALTER - ADD to add single Column

ALTER TABLE customers ADD customer_age varchar2(50);

Using ALTER - ADD to add multiple Columns

ALTER TABLE customers ADD (customer_type varchar2(50), customer_address varchar2(50));

Using ALTER - ADD to add Columns with Default Values

ALTER TABLE customers ADD city varchar2(40) DEFAULT 'Seattle';

Using ALTER - DROP to drop single Column

ALTER TABLE customers DROP COLUMN customer_name;

Using ALTER - DROP to drop multiple Columns

ALTER TABLE customers DROP (customer_type, customer_address);

SQL Statements 6
LIKE Operator and Patterns

WHERE CustomerName LIKE 'a%'


-- Finds any values that start with "a"

WHERE CustomerName LIKE '%a'


-- Finds any values that end with "a"

WHERE CustomerName LIKE '%or%'


-- Finds any values that have "or" in any position

WHERE CustomerName LIKE '_r%'


-- Finds any values that have "r" in the second position

WHERE CustomerName LIKE 'a_%'


-- Finds any values that start with "a" and are at least 2 characters in length

WHERE CustomerName LIKE 'a__%'


-- Finds any values that start with "a" and are at least 3 characters in length

WHERE ContactName LIKE 'a%o'


-- Finds any values that start with "a" and ends with "o"

Using LIKE operator to select all names starting with 's'

SELECT * FROM table1 WHERE name LIKE 's%'

Using CONSTRAINT

CREATE TABLE student (id numeric(4), name varchar2(50), CONSTRAINT check_id CHECK(id BETW
EEN 1 and 10))

During creating the table we have applied a constraint, in which only 1 to 10 rows can
be inserted. So, in below query 12 fields are inserted. If will generate an error message.

INSERT ALL
INTO student(id, name) VALUES (1, 'shristee')
INTO student(id, name) VALUES (2, 'heena')
INTO student(id, name) VALUES (3, 'mohit')
INTO student(id, name) VALUES (4, 'shashank')
INTO student(id, name) VALUES (5, 'avinash')
INTO student(id, name) VALUES (6, 'shweta')

SQL Statements 7
INTO student(id, name) VALUES (7, 'suman')
INTO student(id, name) VALUES (8, 'rohan')
INTO student(id, name) VALUES (9, 'ali')
INTO student(id, name) VALUES (10, 'dolly')
INTO student(id, name) VALUES (11,'mona')
INTO student(id, name) VALUES (12, 'kiran')
SELECT * FROM dual;

But the below code executes smoothly

INSERT ALL
INTO student(id, name) VALUES (1, 'shristee')
INTO student(id, name) VALUES (2, 'heena')
INTO student(id, name) VALUES (3, 'mohit')
INTO student(id, name) VALUES (4, 'shashank')
INTO student(id, name) VALUES (5, 'avinash')
INTO student(id, name) VALUES (6, 'shweta')
INTO student(id, name) VALUES (7, 'suman')
INTO student(id, name) VALUES (8, 'rohan')
INTO student(id, name) VALUES (9, 'ali')
INTO student(id, name) VALUES (10, 'dolly')
SELECT * FROM dual;

SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures the
accuracy and reliability of the data in the table. If there is any violation between the
constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a
column, and table level constraints apply to the whole table.
The following constraints are commonly used in SQL:

NOT NULL  - Ensures that a column cannot have a NULL value

UNIQUE  - Ensures that all values in a column are different

PRIMARY KEY  - A combination of a  NOT NULL  and  UNIQUE . Uniquely identifies each row
in a table

FOREIGN KEY  - Prevents actions that would destroy links between tables

CHECK  - Ensures that the values in a column satisfies a specific condition

DEFAULT  - Sets a default value for a column if no value is specified

SQL Statements 8
CREATE INDEX  - Used to create and retrieve data from the database very quickly

CREATE TABLE table_name (


column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);

Assigning PRIMARY KEY to a Single Column

CREATE TABLE Persons (


ID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);

In the example above there is only ONE PRIMARY KEY (PK_Person). However, the
VALUE of the primary key is made up of TWO COLUMNS (ID + LastName).
To create a PRIMARY KEY constraint on the "ID" column when the table is already
created, use the following SQL:

ALTER TABLE Persons ADD PRIMARY KEY (ID);

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:

SQL Statements 9
ALTER TABLE Persons ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);

If you use ALTER TABLE to add a primary key, the primary key column(s) must have
been declared to not contain NULL values (when the table was first created).

To drop a PRIMARY KEY constraint, use the following SQL -

ALTER TABLE Persons DROP CONSTRAINT PK_Person;

Disabling PRIMARY KEY

ALTER TABLE Persons DISABLE CONSTRAINT PK_Person;

Enabling PRIMARY KEY

ALTER TABLE Persons ENABLE CONSTRAINT PK_Person;

AND & OR Operators

SELECT id, name, age FROM table1 WHERE id > 2 AND age < 28 OR age > 25

AS operator for Aliases

-- For Columns
SELECT id, name AS Student_name FROM table1

-- For Tables
SELECT s.id, s.name FROM table1 s

SQL statement selects only the DISTINCT values from the "Country" column in the
"Customers" table

SELECT DISTINCT Country FROM Customers;

SQL Statements 10
The following SQL statement lists the number of different (distinct) customer
countries:

SELECT COUNT(DISTINCT Country) FROM Customers;

Order By Clause:

-- INCREASING ORDER
SELECT * FROM supplier WHERE supplier_id BETWEEN 500 AND 1000 ORDER BY last_name;

-- DECREASING ORDER
SELECT * FROM supplier WHERE supplier_id BETWEEN 500 AND 1000 ORDER BY last_name DESC;

-- The following SQL statement selects all customers from the "Customers" table, sorted
-- by the "Country" and the "CustomerName" column. This means that it orders by Country,
-- but if some rows have the same Country, it orders them by CustomerName:
SELECT * FROM Customers ORDER BY Country, CustomerName;

-- The following SQL statement selects all customers from the "Customers" table, sorted
-- ascending by the "Country" and descending by the "CustomerName" column:
SELECT * FROM Customers ORDER BY Country ASC, CustomerName DESC;

/***
+------------+----------------------+--------------------+------------+-----------------+-
--------+
| AGENT_CODE | AGENT_NAME | WORKING_AREA | COMMISSION | PHONE_NO |
COUNTRY |
+------------+----------------------+--------------------+------------+-----------------+-
--------+
| A007 | Ramasundar | Bangalore | 0.15 | 077-25814763 |
|
| A003 | Alex | London | 0.13 | 075-12458969 |
|
| A008 | Alford | New York | 0.12 | 044-25874365 |
|
| A011 | Ravi Kumar | Bangalore | 0.15 | 077-45625874 |
|
| A010 | Santakumar | Chennai | 0.14 | 007-22388644 |
|
| A012 | Lucida | San Jose | 0.12 | 044-52981425 |
|
| A005 | Anderson | Brisban | 0.13 | 045-21447739 |
|
| A001 | Subbarao | Bangalore | 0.14 | 077-12346674 |
|
| A002 | Mukesh | Mumbai | 0.11 | 029-12358964 |
|
| A006 | McDen | London | 0.15 | 078-22255588 |
|

SQL Statements 11
| A004 | Ivan | Torento | 0.15 | 008-22544166 |
|
| A009 | Benjamin | Hampshair | 0.11 | 008-22536178 |
|
+------------+----------------------+--------------------+------------+-----------------+-
--------+
***/

-- To get the number of agents for each group of 'working_area' and number of unique 'comm
ission' for
-- each group of 'working_area' by an arranged order on column number 1 i.e. number of age
nts for
-- each group of 'working_area' from the mentioned column list from the 'agents' table, th
e
-- following SQL statement can be used :
SELECT COUNT(agent_name), working_area, COUNT(DISTINCT commission) FROM AGENTS GROUP BY wo
rking_area ORDER BY 1;

/***
ORD_NUM ORD_AMOUNT ADVANCE_AMOUNT ORD_DATE CUST_CODE AGENT_CODE ORD_DESCRIP
TION
---------- ---------- -------------- --------- --------------- --------------- -----------
------
200114 3500 2000 15-AUG-08 C00002 A008
200122 2500 400 16-SEP-08 C00003 A004
200118 500 100 20-JUL-08 C00023 A006
200119 4000 700 16-SEP-08 C00007 A010
200121 1500 600 23-SEP-08 C00008 A004
200130 2500 400 30-JUL-08 C00025 A011
200134 4200 1800 25-SEP-08 C00004 A005
200108 4000 600 15-FEB-08 C00008 A004
200103 1500 700 15-MAY-08 C00021 A005
200105 2500 500 18-JUL-08 C00025 A011
200109 3500 800 30-JUL-08 C00011 A010
200101 3000 1000 15-JUL-08 C00001 A008
200111 1000 300 10-JUL-08 C00020 A008
200104 1500 500 13-MAR-08 C00006 A004
200106 2500 700 20-APR-08 C00005 A002
200125 2000 600 10-OCT-08 C00018 A005
200117 800 200 20-OCT-08 C00014 A001
200123 500 100 16-SEP-08 C00022 A002
200120 500 100 20-JUL-08 C00009 A002
200116 500 100 13-JUL-08 C00010 A009
200124 500 100 20-JUN-08 C00017 A007
200126 500 100 24-JUN-08 C00022 A002
200129 2500 500 20-JUL-08 C00024 A006
200127 2500 400 20-JUL-08 C00015 A003
200128 3500 1500 20-JUL-08 C00009 A002
200135 2000 800 16-SEP-08 C00007 A010
200131 900 150 26-AUG-08 C00012 A012
200133 1200 400 29-JUN-08 C00009 A002
200100 1000 600 08-JAN-08 C00015 A003
200110 3000 500 15-APR-08 C00019 A010
200107 4500 900 30-AUG-08 C00007 A010

SQL Statements 12
200112 2000 400 30-MAY-08 C00016 A007
200113 4000 600 10-JUN-08 C00022 A002
200102 2000 300 25-MAY-08 C00012 A012
***/

-- To get 'ord_date', sum of 'ord_amount' for each group of 'ord_date' and number of agent
s for
-- each group of 'ord_date' from the 'agents' table with the following condition -
-- number of agents for each group of 'ord_date' must be more than 1,

SELECT ORD_DATE, SUM (ORD_AMOUNT), COUNT (*) from ORDERS HAVING COUNT (*) > 1 GROUP BY ORD
_DATE ORDER BY ORD_DATE DESC

-- Sorting by Dates and Time


SELECT UserId, UserName, DATE (IssueDate) AS date1,IssueTime FROM SortByDateAndTime ORDE
R BY DATE (IssueDate) DESC, IssueTime ASC;

GROUP BY Clause

SELECT item, SUM(sale) AS "Total sales" FROM salesdepartment GROUP BY item;

SELECT state, COUNT(*) AS "Number of customers" FROM customers WHERE salary > 10000 GROUP
BY state;

SELECT department, MIN(salary) AS "Lowest salary" FROM employees GROUP BY department;

SELECT department, MAX(salary) AS "Highest salary" FROM employees GROUP BY department;

HAVING Clause

SELECT item, SUM(sale) AS "Total sales" FROM salesdepartment GROUP BY item HAVING SUM(sal
e) < 1000;

SELECT state, COUNT(*) AS "Number of customers" FROM customers WHERE salary > 10000 GROUP
BY state HAVING COUNT(*) >= 2;

SELECT department, MIN(salary) AS "Lowest salary" FROM employees GROUP BY department HAVIN
G MIN(salary) < 15000;

SELECT department, MAX(salary) AS "Highest salary" FROM employees GROUP BY department HAVI
NG MAX(salary) > 30000;

Aggregate Functions

SQL Statements 13
Id Name Salary
-----------------------
1 A 80
2 B 40
3 C 60
4 D 70
5 E 60
6 F Null

Count() :
Count(*) : Returns total number of records .i.e 6.
Count(salary) : Return number of Non Null values over the column salary. i.e 5.
Count(Distinct Salary) :  Return number of distinct Non Null values over the column
salary .i.e 4

Sum() :
sum(salary) :  Sum all Non Null values of Column salary i.e., 310
sum(Distinct salary) : Sum of all distinct Non-Null values i.e., 250.
Avg() :
Avg(salary)  = Sum(salary) / count(salary) = 310/5

Avg(Distinct salary)  = sum(Distinct salary) / Count(Distinct Salary) = 250/4


Min() and Max() :
Min(salary) : Minimum value in the salary column except NULL i.e., 40.
Max(salary) : Maximum value in the salary i.e., 80.

IN Clause

SQL Statements 14
SELECT * FROM table1 WHERE name IN ('shristee', 'dolly', 'sid')

SELECT * FROM table1 WHERE age IN (22, 23, 26, 29)

SELECT * FROM table1 WHERE name NOT IN ('shristee', 'dolly', 'sid')

EXISTS

SELECT name FROM customers c WHERE EXISTS (SELECT 1 FROM orders WHERE customer_id = c.cust
omer_id ) ORDER BY name;

INTERSECT

Suppliers Data

SQL Statements 15
Order_details Data

SELECT supplier_id FROM suppliers INTERSECT SELECT supplier_id FROM order_details;

Changing Password -

ALTER USER user_name IDENTIFIED BY new_password;

SQL Subqueries

SQL Statements 16
-- Consider the CUSTOMERS table having the following records −

/***
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
***/

SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;

-- Result

/***
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
***/

-- Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table.


-- Now to copy the complete CUSTOMERS table into the CUSTOMERS_BKP table, you
-- can use the following syntax.

INSERT INTO CUSTOMERS_BKP


SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS) ;

-- Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table.


-- The following example updates SALARY by 0.25 times in the CUSTOMERS table for all
-- the customers whose AGE is greater than or equal to 27.

UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );

SQL Statements 17
SELECT * FROM CUSTOMERS

-- Result

/***
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 125.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 2125.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
***/

-- Assuming, we have a CUSTOMERS_BKP table available which is a backup of the CUSTOMERS


-- table. The following example deletes the records from the CUSTOMERS table for all the
-- customers whose AGE is greater than or equal to 27.

SQL> DELETE FROM CUSTOMERS


WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );

-- Result

/***
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
***/

-- Details of Employee with Nth Minimum Salary (Take N = 5)

SELECT * FROM EMPLOYEE


WHERE SALARY IN (SELECT MIN (SALARY) AS MIN_SAL FROM EMPLOYEE
WHERE SALARY IN (SELECT DISTINCT TOP 5 SALARY FROM EMPLOYEE ORDER BY SALARY DESC)

-- DETAILS OF ALL EMPLOYEES HAVING SALARY GREATER THAN AVERAGE

SQL Statements 18
SELECT * FROM EMPLOYEE
WHERE SALARY > (SELECT AVERAGE (SALARY) AS AVG_SAL FROM EMPLOYEE)

-- DETAILS OF ALL EMPLOYEES HAVING SALARY GREATER THAN AVERAGE IN THEIR RESPECTIVE DEPARTM
ENT

SELECT * FROM EMPLOYEE E1


WHERE SALARY > (SELECT AVERAGE (SALARY) AS AVG_SAL FROM EMPLOYEE E2
WHERE E1.DEPT == E2.DEPT)

-- DETAILS OF ALL EMPLOYEES INCLUDING THEIR DEPARTMENT'S AVERAGE SALARY

SELECT *, (SELECT AVERAGE (SALARY) FROM EMPLOYEE E2 WHERE E1.DEPT == E2.DEPT) AS DEPT_AVG
FROM EMPLOYEE E1

-- DETAILS OF EMPLOYEES WHOSE SALARY IS GREATER THAN THE AVERAGE SALARY OF ALL THE DEPARTM
ENTS

SELECT * FROM EMPLOYEE


WHERE SALARY > ALL (SELECT DEPT, AVERAGE (SALARY) FROM EMPLOYEE GROUP BY DEPT)

-- * VALUE CAN BE USED WITH OTHER COLUMNS

SELECT *, (SELECT AVG (supplier_id) FROM suppliers) AS avg_id


FROM suppliers
ORDER BY supplier_name ASC, city DESC;

To delete the whole database

DROP DATABASE student_data;

After running the above query whole database will be deleted.

To truncate Student_details table from student_data database.

TRUNCATE TABLE Student_details;

After running the above query Student_details table will be truncated, i.e, the data
will be deleted but the structure will remain in the memory for further operations.

To restore dropped Database using FLASHBACK Command

FLASHBACK TABLE table1 TO BEFORE DROP

SQL Statements 19
To Drop Table so that it doesn't Restore... Use PURGE Command

DROP TABLE table1 PURGE

To Rename a Table

RENAME students_data to students_info

ORACLE JOINS

-- This example will return all rows from "suppliers" and "order1" table where
-- there is a matching supplier_id value in both the suppliers and order1 tables.

SELECT suppliers.supplier_id, suppliers.supplier_name, order1.order_number


FROM suppliers
INNER JOIN order1
ON suppliers.supplier_id = order1.supplier_id;

-- In this example, we are performing left outer join on the already created tables suppli
ers and order1.

-- The following example would return all records from table suppliers and only those reco
rds from
-- table order1 where the join fields are equal.

SELECT suppliers.supplier_id, suppliers.supplier_name, order1.order_number


FROM suppliers
LEFT OUTER JOIN order1
ON suppliers.supplier_id = order1.supplier_id;

-- In this example, we are performing right outer join on the already created tables Suppl
iers and order1.
-- The following example would return all rows from the order1 table and only those rows f
rom the
-- suppliers table where the join condition is met.

SELECT order1.order_number, order1.city, suppliers.supplier_name


FROM suppliers
RIGHT OUTER JOIN order1
ON suppliers.supplier_id = order1.supplier_id;

-- In this example, we are performing full outer join on the already created tables suppli
ers and order1.

SQL Statements 20
-- The following example will return all rows from the suppliers table and all rows from t
he order1
-- table and whenever the join condition is not met, it places the NULL value.

SELECT suppliers.supplier_id, suppliers.supplier_name, order1.order_number


FROM suppliers
FULL OUTER JOIN order1
ON suppliers.supplier_id = order1.supplier_id;

-- EQUI JOIN IN TWO WAYS

SELECT agents.agent_city,customer.last_name,
customer.first_name
FROM agents,customer
WHERE agents.agent_id=customer.customer_id;

SELECT agents.agent_city,customer.last_name,
customer.first_name
FROM agents
JOIN customer
ON agents.agent_id=customer.customer_id

-- SELF JOIN

/***
NAME AGE ADDRESS SALARY
Alex 24 NEWYORK 25000
Pandian 32 Chennai 32000
Lalu 45 Bihar 56000
Bholu 19 Haridwar 12000
***/

SELECT a.name, b.age, a.SALARY


FROM CUSTOMERS a, CUSTOMERS b
WHERE a.SALARY < b.SALARY;

/***
NAME AGE SALARY
Alex 24 25000
Alex 45 25000
Pandian 45 32000
Bholu 24 12000
Bholu 32 12000
Bholu 45 12000
***/

-- CROSS JOIN

SELECT * FROM customer,supplier

SQL Statements 21
ANTI JOIN
Anti-join is used to make the queries run faster. It is a very powerful SQL construct
Oracle offers for faster queries.
Anti-join between two tables returns rows from the first table where no matches are
found in the second table.

It is opposite of a semi-join. An anti-join returns one copy of each row in the first table
for which no match is found.
Anti-joins are written using the NOT EXISTS or NOT IN constructs.

SELECT departments.department_id, departments.department_name


FROM departments
WHERE NOT EXISTS
(
SELECT 1
FROM customer
WHERE customer.department_id = departments.department_id
)
ORDER BY departments.department_id;

SQL Statements 22
SEMI JOIN
Semi-join is introduced in Oracle 8.0. It provides an efficient method of performing a
WHERE EXISTS sub-query.
A semi-join returns one copy of each row in first table for which at least one match is
found.
Semi-joins are written using the EXISTS construct.

SQL Statements 23
SELECT departments.department_id, departments.department_name
FROM departments
WHERE EXISTS
(
SELECT 1
FROM customer
WHERE customer.department_id = departments.department_id
)
ORDER BY departments.department_id;

Correlated subqueries are used for row-by-row processing. Each subquery is executed
once for every row of the outer query.

SQL Statements 24
A correlated subquery is evaluated once for each row processed by the parent
statement. The parent statement can be a
SELECT, UPDATE, or DELETE statement.

SELECT column1, column2, ....


FROM table1 outer
WHERE column1 operator
(SELECT column1, column2
FROM table2
WHERE expr1 =
outer.expr2);

A correlated subquery is one way of reading every row in a table and comparing values
in each row against related data.
It is used whenever a subquery must return a different result or set of results for each
candidate row considered by the main query.
In other words, you can use a correlated subquery to answer a multipart question whose
answer depends on the value in each row processed by the parent statement.

Nested Subqueries Versus Correlated Subqueries :


With a normal nested subquery, the inner SELECT query runs first and executes once,
returning values to be used by the main query.
A correlated subquery, however, executes once for each candidate row considered by the
outer query.

In other words, the inner query is driven by the outer query.NOTE : You can also use
the ANY and ALL operator in a correlated subquery.
EXAMPLE of Correlated Subqueries : 
Find all the employees who earn more than the average salary in their department.

SELECT last_name, salary, department_id


FROM employees outer
WHERE salary >
(SELECT AVG(salary)
FROM employees
WHERE department_id =
outer.department_id);

SQL Statements 25
Other use of correlation are in UPDATE and DELETE

CORRELATED UPDATE :

UPDATE table1 alias1


SET column = (SELECT expression
FROM table2 alias2
WHERE alias1.column =
alias2.column);

Use a correlated subquery to update rows in one table based on rows from another
table.

CORRELATED DELETE :

DELETE FROM table1 alias1


WHERE column1 operator
(SELECT expression
FROM table2 alias2
WHERE alias1.column = alias2.column);

Use a correlated subquery to delete rows in one table based on the rows from another
table.

Using the EXISTS Operator :


The EXISTS operator tests for existence of rows in the results set of the subquery.
If a subquery row value is found the condition is flagged TRUE and the search does not
continue in the inner query,
and if it is not found then the condition is flagged FALSE and the search continues in
the inner query.
EXAMPLE of using EXIST operator :Find employees who have at least one person
reporting to them.

SELECT employee_id, last_name, job_id, department_id


FROM employees outer

SQL Statements 26
WHERE EXISTS ( SELECT ’X’
FROM employees
WHERE manager_id =
outer.employee_id);

OUTPUT :

EXAMPLE of using NOT EXIST operator :


Find all departments that do not have any employees.

SELECT department_id, department_name


FROM departments d
WHERE NOT EXISTS (SELECT ’X’
FROM employees
WHERE department_id
= d.department_id);

OUTPUT :

SQL Statements 27
Scalar Functions

-- Converting names of students from the table Students to uppercase.

SELECT UCASE(NAME) FROM Students;

/***
Output:
NAME
HARSH
SURESH
PRATIK
DHANRAJ
RAM
***/

-- Converting names of students from the table Students to lowercase.

SELECT LCASE(NAME) FROM Students;

/***
Output:
NAME
harsh
suresh
pratik
dhanraj
ram
***/

-- Fetching first four characters of names of students from the Students table.

SQL Statements 28
SELECT MID(NAME,1,4) FROM Students;

/***
Output:
NAME
HARS
SURE
PRAT
DHAN
RAM
***/

-- Fetching length of names of students from Students table.

SELECT LENGTH(NAME) FROM Students;

/***
Output:
NAME
5
6
6
7
3
***/

-- Fetching maximum marks among students from the Students table.

SELECT ROUND(MARKS,0) FROM table_name;

/***
Output:
MARKS
90
50
80
95
85
***/

-- Fetching current system time.

SELECT NAME, NOW() AS DateTime FROM Students;

/***
Output:
NAME DateTime
HARSH 1/13/2017 1:30:11 PM
SURESH 1/13/2017 1:30:11 PM
PRATIK 1/13/2017 1:30:11 PM
DHANRAJ 1/13/2017 1:30:11 PM
RAM 1/13/2017 1:30:11 PM
***/

SQL Statements 29
-- Formatting current date as 'YYYY-MM-DD'.

SELECT NAME, FORMAT(Now(),'YYYY-MM-DD') AS Date FROM Students;

/***
Output:
NAME Date
HARSH 2017-01-13
SURESH 2017-01-13
PRATIK 2017-01-13
DHANRAJ 2017-01-13
RAM 2017-01-13
***/

ALL and ANY


Consider the following Products Table and OrderDetails Table,

Products Table

OrderDetails Table

SQL Statements 30
Queries

Find the name of the all the product.Output:

SELECT ALL ProductName

FROM Products

WHERE TRUE;

Find the name of the product if all the records in the OrderDetails has
Quantity either equal to 6 or 2.Output:

SQL Statements 31
SELECT ProductName

FROM Products

WHERE ProductID = ALL (SELECT ProductId

FROM OrderDetails

WHERE Quantity = 6 OR Quantity = 2);

Find the OrderID whose maximum Quantity among all product of that
OrderID is greater than average quantity of all OrderID.Output:

SELECT OrderID

FROM OrderDetails

GROUP BY OrderID

HAVING max(Quantity) > ALL (SELECT avg(Quantity)

FROM OrderDetails

GROUP BY OrderID);

Find the Distinct CategoryID of the products which have any record in
OrderDetails Table.Output:

SELECT DISTINCT CategoryID

SQL Statements 32
FROM Products

WHERE ProductID = ANY (SELECT ProductID

FROM OrderDetails);

Finds any records in the OrderDetails table that Quantity = 9.

SELECT ProductName

FROM Products

WHERE ProductID = ANY (SELECT ProductID

FROM OrderDetails

WHERE Quantity = 9);

Arithmetic Operators are:

+ [Addition]
- [Subtraction]

SQL Statements 33
/ [Division]
* [Multiplication]
% [Modulus]

Addition (+) :
It is used to perform addition operation on the data items, items include
either single column or multiple columns.
Implementation:

SELECT employee_id, employee_name, salary, salary + 100


AS "salary + 100" FROM addition;

Output:

employee_id employee_name salary salary+100

1 alex 25000 25100

2 rr 55000 55100
3 jpm 52000 52100

4 ggshmr 12312 12412

Here we have done addition of 100 to each Employee's salary i.e, addition
operation on single column.
Let's perform addition of 2 columns:

SELECT employee_id, employee_name, salary, salary + employee_id


AS "salary + employee_id" FROM addition;

Output

employee_id employee_name salary salary+employee_id

1 alex 25000 25001

2 rr 55000 55002

SQL Statements 34
employee_id employee_name salary salary+employee_id

3 jpm 52000 52003

4 ggshmr 12312 12316

Here we have done addition of 2 columns with each other i.e, each employee's
employee_id is added with its salary.

Subtraction (-) :
It is use to perform subtraction operation on the data items, items include
either single column or multiple columns.

Implementation:

SELECT employee_id, employee_name, salary, salary - 100


AS "salary - 100" FROM subtraction;

Output

employee_id employee_name salary salary-100

12 Finch 15000 14900

22 Peter 25000 24900

32 Warner 5600 5500

42 Watson 90000 89900

Here we have done subtraction of 100 to each Employee's salary i.e, subtraction
operation on single column.
Let's perform subtraction of 2 columns:

SELECT employee_id, employee_name, salary, salary - employee_id


AS "salary - employee_id" FROM subtraction;

Output

employee_id employee_name salary salary - employee_id

SQL Statements 35
employee_id employee_name salary salary - employee_id

12 Finch 15000 14988


22 Peter 25000 24978

32 Warner 5600 5568

42 Watson 90000 89958

Here we have done subtraction of 2 columns with each other i.e, each
employee's employee_id is subtracted from its salary.

Multiplication (*) :
It is use to perform multiplication of data items.
Implementation:

SELECT employee_id, employee_name, salary, salary * 100


AS "salary * 100" FROM addition;

Output:

employee_id employee_name salary salary * 100

1 Finch 25000 2500000

2 Peter 55000 5500000

3 Warner 52000 5200000


4 Watson 12312 1231200

Here we have done multiplication of 100 to each Employee's salary i.e,


multiplication operation on single column.
Let's perform multiplication of 2 columns:

SELECT employee_id, employee_name, salary, salary * employee_id


AS "salary * employee_id" FROM addition;

Output

SQL Statements 36
employee_id employee_name salary salary * employee_id

1 Finch 25000 25000

2 Peter 55000 110000

3 Warner 52000 156000

4 Watson 12312 49248

Here we have done multiplication of 2 columns with each other i.e, each
employee's employee_id is multiplied with its salary.

Modulus ( % ) :
It is use to get remainder when one data is divided by another.
Implementation:

SELECT employee_id, employee_name, salary, salary % 25000


AS "salary % 25000" FROM addition;

Output

employee_id employee_name salary salary % 25000

1 Finch 25000 0
2 Peter 55000 5000

3 Warner 52000 2000

4 Watson 12312 12312

Here we have done modulus of 100 to each Employee's salary i.e, modulus
operation on single column.
Let's perform
modulus operation between 2 columns:

SELECT employee_id, employee_name, salary, salary % employee_id


AS "salary % employee_id" FROM addition;

SQL Statements 37
Output

employee_id employee_name salary salary % employee_id

1 Finch 25000 0
2 Peter 55000 0

3 Warner 52000 1

4 Watson 12312 0

Here we have done modulus of 2 columns with each other i.e, each employee's
salary is divided with its id and corresponding remainder is shown.
Basically, modulus is use to check whether a number is Even or Odd. Suppose
a given number if divided by 2 and gives 1 as remainder, then it is an odd
number
or if on dividing by 2 and gives 0 as remainder, then it is an even number.

Concept of NULL :
If we perform any arithmetic operation on NULL, then answer is always null.
Implementation:

SELECT employee_id, employee_name, salary, type, type + 100


AS "type+100" FROM addition;

Output

employee_id employee_name salary type type + 100

1 Finch 25000 NULL NULL

2 Peter 55000 NULL NULL

3 Warner 52000 NULL NULL

4 Watson 12312 NULL NULL

Here output always came null, since performing any operation on null will
always result in a null value.

SQL Statements 38
Note: Make sure that NULL is unavailable, unassigned, unknown. Null is not
same as blank space or zero.

A role is created to ease setup and maintenance of the security model. It is a


named group of related privileges that can be granted to the user.
When there are many users in a database it becomes difficult to grant or revoke
privileges to users. Therefore, if you define roles:

You can grant or revoke privileges to users, thereby automatically granting


or revoking privileges.

You can either create Roles or use the system roles pre-defined.

Some of the privileges granted to the system roles are as given below:

System Privileges granted to the Role


Roles

Create table, Create view, Create synonym, Create sequence, Create session
Connect
etc.
Create Procedure, Create Sequence, Create Table, Create Trigger etc. The
Resource
primary usage of the Resource role is to restrict access to database objects.

DBA All system privileges

Creating and Assigning a Role -


First, the (Database Administrator)DBA must create the role. Then the DBA can
assign privileges to the role and users to the role.
Syntax -

CREATE ROLE manager;


Role created.

In the syntax:
'manager' is the name of the role to be created.

SQL Statements 39
Now that the role is created, the DBA can use the GRANT statement to
assign users to the role as well as assign privileges to the role.

It's easier to GRANT or REVOKE privileges to the users through a role


rather than assigning a privilege directly to every user.

If a role is identified by a password, then GRANT or REVOKE privileges


have to be identified by the password.

Grant privileges to a role -

GRANT create table, create view


TO manager;
Grant succeeded.

Grant a role to users

GRANT manager TO SAM, STARK;


Grant succeeded.

Revoke privilege from a Role :

REVOKE create table FROM manager;

Drop a Role :

DROP ROLE manager;

Explanation -
Firstly it creates a manager role and then allows managers to create tables and
views. It then grants Sam and Stark the role of managers.
Now Sam and Stark can create tables and views. If users have multiple roles
granted to them, they receive all of the privileges associated with all of the
roles.

SQL Statements 40
Then create table privilege is removed from role 'manager' using Revoke.The
role is dropped from the database using drop.

SQL Statements 41

You might also like