0% found this document useful (0 votes)
85 views

SQL Notes

The document discusses various SQL command types including: 1. Data Definition Language (DDL) commands like CREATE, ALTER, and DROP are used to define and modify database schemas and structures. 2. Data Manipulation Language (DML) commands like INSERT, UPDATE, and DELETE are used to manage data and are not automatically committed. 3. Data Control Language (DCL) commands like GRANT and REVOKE control user access privileges. 4. Transaction Control Language (TCL) commands like COMMIT, ROLLBACK, and SAVEPOINT manage transactions and committing or rolling back changes to the database.

Uploaded by

sumanth v
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views

SQL Notes

The document discusses various SQL command types including: 1. Data Definition Language (DDL) commands like CREATE, ALTER, and DROP are used to define and modify database schemas and structures. 2. Data Manipulation Language (DML) commands like INSERT, UPDATE, and DELETE are used to manage data and are not automatically committed. 3. Data Control Language (DCL) commands like GRANT and REVOKE control user access privileges. 4. Transaction Control Language (TCL) commands like COMMIT, ROLLBACK, and SAVEPOINT manage transactions and committing or rolling back changes to the database.

Uploaded by

sumanth v
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

SQL COMMAND TYPES

1. Data Definition Language (DDL)


• DDL changes the structure of the table like creating a table, deleting a table,
altering a table, etc.
• 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:
• CREATE
• ALTER
• DROP
• TRUNCATE
A.CREATE TABLE
• In Oracle, CREATE TABLE statement is used to create a new table in the database.
• To create a table, you have to name that table and define its columns and datatype
for each column .
• Syntax:
• CREATE TABLE table_name  
• (   
•   column1 datatype [ NULL | NOT NULL ],  
•   column2 datatype [ NULL | NOT NULL ],  
•   ...  
•   column_n datatype [ NULL | NOT NULL ]  
• );  
B. ALTER TABLE
• In Oracle, ALTER TABLE statement specifies how to add, modify, drop or delete columns in a table. It is also
used to rename a table.

1. Add column in a table


Syntax:
ALTER TABLE table_name  
  ADD column_name datatype; 
Example:
ALTER TABLE customers 
   ADD customer_age varchar2(50);  

2. Modify Column Of A Table

• Syntax:
ALTER TABLE table_name  
  MODIFY column_name column_type;
Example:
ALTER TABLE customers 
   Modify customer_age age(3);
3. Drop Column Of A Table

Syntax:
ALTER TABLE table_name  
   DROP COLUMN column_name;  
Example:
ALTER TABLE customers  
   DROP COLUMN customer_name; 

4.  Rename Column Of A Table


Syntax:
ALTER TABLE table_name  
   RENAME COLUMN old_name to new_name;  
Example:
ALTER TABLE customers  
  RENAME COLUMN customer_name to cname; 
5.  Rename A Table
Syntax:
 RENAME old_nameTO new_table_name;   
Example:
RENAME Customers TO retailers;  
C. DROP TABLE
• Oracle DROP TABLE statement is used to remove or delete a table from the Oracle database.
Syntax
DROP TABLE table_name  
Example
DROP TABLE customers;
  
D. TRUNCATE
• In Oracle, the truncate statement is used to remove all the records of a table but
the structure of the table remains same.
Syntax
Truncate table table_name;
   Example
Truncate TABLE customers;
  
2. Data Manipulation Language (DML)
• DML commands are used to modify the database. It is responsible for all form of
changes in the database.
• The command of DML is not auto-committed that means it can't permanently save
all the changes in the database. They can be rollback.
• Here are some commands that come under DML:
• INSERT
• UPDATE
• 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   (column_name1,column_name2,column_namen) 
  VALUES (value1, value2, value3, .... valueN);
example:
INSERT INTO customer VALUES (‘Sonoo’, ’DBMS’);  

B. UPDATE
• This command is used to update or modify the value of a column in the table.
Syntax:
UPDATE table_name SET column_name1= value1 [WHERE CONDITION]
example:
UPDATE customer    
SET User_Name = 'Sonoo'    
WHERE  customer_Id = 3;
C. DELETE
• It is used to remove one or more row from a table.
Syntax:
DELETE FROM table_name [WHERE condition];  

example:
DELETE FROM Customer  WHERE Author=‘Sonoo’;  
3. Data Control Language
• DCL commands are used to grant and take back authority from any database user.
• Here are some commands that come under DCL:
A. Grant
B. Revoke
A.  Grant
•  It is used to give user access privileges to a database.
Syntax:
GRANT operations on table_name To From_User, To_user;
example:
GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;  
  
A.  Revoke
•  It is used to take back permissions from the user.
Syntax:
Revoke operations on table_name From user1, user2;
example:
REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;  
 
4. Transaction Control Language
• TCL commands can only use with DML commands like INSERT, 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:
A. COMMIT
B. ROLLBACK
C. SAVEPOINT
A.  Commit
•  Commit command is used to save all the transactions to the database..
• Once we done the commit then we cannot rollback.
Syntax:
COMMIT; 
example:
DELETE FROM CUSTOMERS  WHERE AGE = 25;  
COMMIT;  

B. Rollback
• Rollback 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 back to a certain point without rolling back the
entire transaction.
Syntax:
SAVEPOINT SAVEPOINT_NAME;  
 
example:
SAVEPOINT Dinga;  
5. Data Query Language
• DQL is used to fetch the data from the database.
• It uses only one command:
select

A. SELECT
• This is the same as the projection operation of relational algebra. It is used to
select the attribute based on the condition described by WHERE clause .
Syntax:

SELECT expressions FROM TABLES  WHERE conditions;  
example:

SELECT emp_name FROM employee WHERE age > 20;  
Datatypes

CHAR VARCHAR VARCHAR2 NUMBER DATE


Datatypes
1) CHAR(size)
It is used to store character data within the predefined length.

2) VARCHAR(SIZE)
It is Used to store alphanumeric values. It can be stored up to 2000 bytes.

3) VARCHAR2(size)
It is Used to store alphanumeric values. It can be stored up to 4000 bytes.

4) NUMBER(p, s)
it is used to store numeric values. It may be int, float or etc.

5) DATE
It is used to store a valid date-time format with a fixed length. Its range varies from
January 1, 4712 BC to December 31, 9999 AD.

Note:- The main difference between varchar and varchar2 is , where varchar2
compresses the storage size where as that varchar doesn’t compresses the
storage size
Constraints

• It Is used to restricts the values in a database.

1) Primary Key
Primary key is used to represent unique values, and it cannot be null. Or it is a
combination of unique and notnull constraints.
In a table, there can be only one primary key.
Syntax:
CREATE TABLE table_name  (  column1 datatype primary key);  

Example:
CREATE TABLE Test2(ID Number PRIMARY KEY); 
2) Unique
It cannot allow Duplicate values.
It allows only one null value.
Syntax:
CREATE TABLE table_name  (  column1 datatype Unique);  

Example:
CREATE TABLE Test2(ID Number  Unique); 

3) Default
The DEFAULT constraint is used to set a default value for a column.
The default value will be added to all new records, if no other value is specified.
Syntax:
CREATE TABLE table_name  (  column1 datatype default=‘some values’);  

Example:
CREATE TABLE Test2(ID Number  default 1 ); 
4) Null
It allows only null value.
It can allow Duplicate null values.

Syntax:
CREATE TABLE table_name  (  column1 datatype null);  

Example:
CREATE TABLE Test2(ID Number null); 

5) Not Null
The NOT NULL constraint enforces a column to NOT accept NULL values.

Syntax:
CREATE TABLE table_name  (  column1 datatype not null);  

Example:
CREATE TABLE Test2(ID Number  not null); 
Operators

And OR NOT LIKE IN BETWEEN


Operators
1.AND
• The AND operator allows the existence of multiple conditions in an SQL statement's
WHERE clause and if both conditions are true then it will execute a query.

example:-
Select * from emp where empid>1 AND empid<5;
2.OR
• The OR operator is used to combine multiple conditions in an SQL statement's WHERE
clause and if any one condition is true then it will execute a query. .

example:-
Select * from emp where empid>1 OR empid=1;

3.NOT
• The NOT operator reverses the meaning of the logical operator with which it is used. Eg:
NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.

example:-
Select * from emp1 where not empid=2;
4.LIKE
• The LIKE operator is used to compare a value to similar values using wildcard
operators

example:-
select * from emp1 where ename like 'r%';

5.BETWEEN
• The BETWEEN operator is used to search for values that are within a set of values,
given the minimum value and the maximum value.

example:-
SELECT * FROM emp1 WHERE empid BETWEEN 2 AND 4;
6.IN
• The IN operator is used to compare a value to a list of similar values that have been
specified.

example:-
select * from emp1 where empid in (3);
SQL Clauses

Where Having Group By Order By


1. Where
• The WHERE clause is used to filter records.
• It is used to extract only those records that fulfill a specified condition.

Syntax:
Select * from table_name where condition

Example:
Select * from Emp1 where EmpId=1;
2. Having
The HAVING clause was added to SQL because the WHERE keyword cannot be
used with aggregate (min, max, sum, count, etc…) functions.
Syntax:
Select * from table_name Having condition

Example:
Select * from Emp1 Having (Sal*Bonus)>30000;
3. Group by
• The Group by clause is used to group the records.
• The GROUP BY statement is often used with aggregate functions
(COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more
columns.

Syntax:
Select column_name from table_name group by column_name;

Example:
select sal from emp1 group by sal;

4. Order By
• The Order by clause is used to sort the records.
Syntax:
Select column_name from table_name order by column_name;

Example:
select sal from emp1 order by sal;
SQL Aliases
•SQL aliases are used to give a table, or a column in a table, a temporary name.
•Aliases are often used to make column names more readable.
•An alias only exists for the duration of that query.
•An alias is created with the AS keyword.

2. Alias Table
1. Alias Column
Syntax
Syntax
• select column_name(s)
• select column_name as alias_name
from table_name as alias_name;
from table_name;
Example
Example
select empid from emp1
select empid as Eid
as Emp2;
from Emp1;
DISTINCT
• It is used to filtering duplicate data from records.
• It gives the output in default sorting order.

Syntax
select distinct column_1 from table_name;

Example
select distinct sal, ename from Emp1;
Union Union All
• This keyword is used to remove • This keyword is used to display all the
duplicate record between the two Duplicate records In between two
table, if the column fields are table, if the column fields are
matched. matched.

Syntax Syntax
Select * from table1 union select * Select * from table1 union all select *
from table2; from table2;

Example Example
select * from emp1 union select * select * from emp1 union all select *
from emp2; from emp2;
String
Substring Instring
• Sub string is a part of a Parent String. • It will give output of a character as
• It will give output as character or index number.
String. Syntax
Syntax select instr(‘String',’matching
select substr(‘String', staring parameter',starting index
index of character, ending index of count,appearance of character)
character) from dual; from dual;
Example Example
select substr('harish is learning select instr('harish is learning
sql’,1,1) from dual; sql','i',1,1) from dual;

Note:- if we give Starting Index as Negetive Value then it will Check the Apperance of
charater from right to left but it will count the index value from left to right.
Sub Query
• A Subquery or Inner query or a Nested query is a query within another SQL query.
• Subqueries must be enclosed within parentheses.

Syntax
Select column1, column2, column3 from (select column1, column2, column3,
column4, column5 from table_name) ;
Example
Select empid, ename from (select empid, ename, salary, position from emp1) ;
JOINS
• Join is a query that is used to combine rows from two or more tables, views, or
materialized views. It retrieves data from multiple tables and creates a new table.

Types of Joins
1) Inner Join.
2) Outer Join
a. Left outer join.
b. Right outer join.
3) Full Join.
4) Self Join.
Working Representation of Joins

INNER JOIN LEFT JOIN

RIGHT JOIN
1. Inner Join
• Inner Join is the simplest and most common type of join.
• It is also known as simple join.
• It returns only Duplicate values in between multiple tables.
Syntax:
select columns  from table1 inner join table2  on table1.column =
 table2.column;   
Example:
select orders.orders_id, orders.orders_name, from orders inner join supplier on
orders.orders_id=supplier.supplier_id;

2. A). Left Join


• It returns all duplicate record between multiple table and also it returns remaining
records of left table.
Syntax:
select columns  from table1 Left join table2  on table1.column =
 table2.column;   

Example:
select orders.orders_id, orders.orders_name, from orders Left join supplier on
orders.orders_id=supplier.supplier_id;
2. B). Right Join
• It returns all duplicate record between multiple table and also it returns remaining records of
right table.
Syntax:
select columns  from table1 right join table2  on table1.column =
 table2.column;   

Example:
select orders.orders_id, orders.orders_name, from orders right join supplier on
orders.orders_id=supplier.supplier_id;

3. Full Join
• It returns all duplicate record between multiple table and also it returns remaining records of
right and left table.

Syntax:
select columns  from table1 Full join table2  on table1.column =
 table2.column;   
Example:
select orders.orders_id, orders.orders_name, from orders Full join supplier on
orders.orders_id=supplier.supplier_id;
RANK()
• The RANK() function is an analytic function that calculates the rank of a value in a set of
values.
• The RANK() function returns the same rank for the rows with the same values. It adds
the number of tied rows to the tied rank to calculate the next rank. Therefore, the ranks
may not be consecutive numbers.
Syntax:
SELECT rank() over (orderby column_name) from table_name;   

Example:
SELECT rank() over (orderby Students_score) from students;   
DENSE_RANK()
• The DENSE_RANK() function is an analytic function that calculates the rank of a value in
a set of values.
• Unlike the RANK() function, the DENSE_RANK() function returns rank values as
consecutive integers. It does not skip rank in case of ties. Rows with the same values for
the rank criteria will receive the same rank values.
Syntax:
SELECT dense_rank() over (orderby column_name) from table_name;   

Example:
SELECT dense_rank() over (orderby Students_score) from students;   
LEAD
• It allows you to access the following row from the current row without using a self-
join.

Syntax:
SELECT lead ( column_name,no of shifiting record(offset) ,default )over (order
by column_name ) from table_name;   

Example:
SELECT lead ( student_id, 1 , 05 )over (order by student_name) from
student;      
LAG
• It allows you to access the following row from the current row without using a self-
join.

Syntax:
SELECT lag ( column_name,no of shifiting record(offset) ,default )over (order
by column_name ) from table_name;   

Example:
SELECT lag ( student_id, 1 , 05 )over (order by student_name) from
student;      
LISTAGG
• The Oracle LISTAGG() function is an aggregation function that transforms data from
multiple rows into a single list of values separated by a specified delimiter.
Syntax:
SELECT listagg ( column_name,delimeter ) within group (order by
column_name ) from table_name;   

Example:
SELECT lag ( student_id, 1 , 05 )over (order by student_name) from
student;      

You might also like