SQ L Presentation 1
SQ L Presentation 1
What is Data?
Any Useful information is a data.
In simple words data can be facts related to any
object in consideration
For example your name, age, height, weight, etc are
some data related to you. A picture , image , file , pdf
etc can also be considered data
What is Database ?
A database is a systematic collection of data.
Databases support storage and manipulation of data.
Databases make data management easy
Types of DBMS
Hierarchical - this type of DBMS employs the "parent-child" relationship of storing
data.
The windows registry used in Windows OS is an example of a hierarchical database.
Note :-
If we install any of the database related software(s) – we can
create our own database, we can create our own tables and we
can store the data inside it.
When we install any database s/w(s) – a part of hard disk will
be designated / reserved to perform database related activities
A database can also contain other database objects like views,
indexes, stored procedures, functions, triggers etc, apart from
tables.
Types of Constraints
NOT NULL
UNIQUE
Primary Key
Foreign Key
Check
NULL
NULL is nothing, it is neither zero nor blank space
It will not occupy any space in the memory
Two NULLS are never same in Oracle.
NULL represents unknown value
Any arithmetic operation we perform on NULL will result in NULL
itself. For ex, 100000 + NULL = NULL ; 100000 * NULL = NULL
NOT NULL
- NOT NULL will ensure atleast some value should be present in a column
UNIQUE
It will not allow any duplicates in a column
UNIQUE column can take multiple NULL (s)
Primary Key
It is the combination of NOT NULL and UNIQUE
Only one PK is allowed in a table
PK identifies a record uniquely in a table
Creation of PK is not mandatory, but it is highly recommended to create
Foreign Key
FK creates relationship between any two tables
FK is also called as referential integrity constraints
FK is created on the child table
FK can take both NULL and duplicate values
To create FK, the master table should have PK defined on the common
column of the master table
We can have more than 1 FK in a given table
CHECK
It is used to provide additional validations as per the customer
requirements.
Troubleshooting Oracle
Error 1
The account is locked
Steps to rectify the error
Login as username – ‘system’ & password – ‘manager’
or ‘password – ‘tiger’
SQL > show user ;
User is “SYSTEM”
What is SQL?
Structured Query language (SQL) pronounced as
"S-Q-L" or sometimes as "See-Quel"is actually
the standard language for dealing with Relational
SQL Statements
1 Select Data retrieval language
2 Insert Data manipulation Language
Update
Delete
3 Create Data definition language
Alter
Drop
Rename
Truncate
4 Commit Transaction Control Language
Rollback
Save Point Data transaction Language
5 Grant, Revoke Data Control language
DQL
SELECT:
It is the statement used to read data from the table.
Projection:
Syntax:
Select * | {[Distinct] Column| Expression [Aliase],…}
From table
Column Alias
Sql>edit C:\xyz.txt
12. To record the output that is taking place in sql plus we use ‘SPOOL’
SQL> Spool
Operators
Operators are classified into,
Arithmetic Operators ( +, - , * , / )
Relational Operators ( > , < , >= , <= , = , < > or != - not
equals to )
Logical Operators ( NOT, AND, OR )
Special Operators ( IN , LIKE , BETWEEN , IS )
1 Arithmetic Operator
2 Concatenation
3 Comparison
4 Is, Like, In
5 Between
6 Not
7 AND
8 OR
SELECTION:
Limiting the Rows Selected
Select *|{[Distinct ] column|expression [aliase]…}
From table
Where condition(s)]
SQL> Select *
2 from emp
3 where ename='ALLEN';
Ex: Select *
From emp
Where job=‘MANAGER’
1. List all the employees in dept 20.
2. List the employee earning more than Rs 2500;
3. Display all the salesmen
4) List the employees whose name is having letter ‘E’ as the last but
one character
5) List all the employees whose name is having letter ‘R’ in the 3 rd
position
6) List all the employees who are having exactly 5 characters in their
BETWEEN operator – used for searching based on range of
values.
4) List all the employees except those who are working in dept
10 & 20.
5) List the employees whose name does not start with ‘S’
Assignments.
4) Display all the employees whose job has string ‘MAN’ in it.
SORTING
It arranges the data either in ascending / descending order
Ascending – ASC / Descending – DESC
We can sort the data using ORDER BY
NOTE :-
1.ORDER BY should be used always as the last statement in
the SQL query.
2. You can sort by a column that is not in the select case.
3. Entire row will be ordered not only selected columns will be
displayed in order.
Ex:
SQL> SELECT * FROM EMP WHERE
MOD(SAL,2)=1;
1.Display all the employees whose job has
string ‘MAN’
2.Display all the employees whose name has
‘L’ as third character.
3.Display the result in the following format,
first character in lower case rest in
uppercase.
4.Display all the employees which has at lest
2L’s in it.
5.Display the number of occurrence of
substring in a string.
Display the number of L’s in each name
6. Display all the employees whose name is
palindrome
Working with Dates:
Oracle database stores dates in an internal numeric format:
Century, Year, Month, day, hours, minutes, Seconds.
The default date display format is DD-MM-YY
HAVING
‘Having’ is used to filter the grouped data.
‘Where’ is used to filter the non grouped data.
RESTRICTIONS ON GROUPING
Note 1- we can select only the columns that are part of ‘group by’
statement
If we try selecting other columns, we will get an error
Syntax of a sub-query
OUTER QUERY
Select …
From …
Where … ( select …
From …
Where …
)
INNER QUERY
CARTESIAN JOIN
- It is based on Cartesian product theory.
Display employee name along with the department name
INNER JOIN
Inner join are also called as equijoins.
They return the matching records between the tables.
In the real time scenarios, this is the most frequently used Join.
OUTER JOIN
It returns both matching and non-matching records
SELF JOIN
Joining a table to itself is called self join
5) Display employee name along with their manager name
6) Display the employees who are getting the same salary
Equijoin:
1. Display all the managers and clerks who work in
accounts and marketing departments.
2. Display all the salesman who are not located at
DALLAS
3. Select all the employees who work in DALLAS
OUTER JOIN
4. Get matching as well as non matching records from
both the table
SELF JOIN:
1. Get all the employees who work in the same department as
of scott
SELECT A.ENAME,B.ENAME
FROM EMP A, EMP B
WHERE A.DEPTNO=B.DEPTNO
AND A.ENAME='SCOTT‘
For ex, Display the employee who is earning the highest salary
SQL> select * from emp A
2 where 0=(Select count(distinct(sal)) from emp B where
A.Sal<B.Sal);
1) Display the least salary from the employee table.
Before we study the Create command, let us first study the some
of the basic datatypes we use in SQL.
1) CHAR :-
It stores the fixed length character data.
It can store the alphanumeric data (i.e, numbers and characters).
2) VARCHAR
It stores the variable length character data
It can store alphanumeric data.
Another difference is : -
In char, maximum value we can store is 2000 characters
In varchar, maximum value we can store is 4000 characters.
3) NUMBER
- it stores numeric data.
For ex – 1) sal number(4) ;
Here the maximum possible value is 9999.
6) CLOB
Stands for – Character Large Object
It stores plain character data like varchar field upto 4GB.
NOTE :-
varchar2 – from 10g, varchar & varchar2 are the same.
Earlier, varchar was supporting upto 2000 characters and varchar2
was supporting upto 4000 characters.
Create the following tables
PRODUCTS
ProdID ( PK )
ProdName ( Not Null )
Qty ( Chk > 0 )
Description
ORDERS
The new table orders has been created. We can see from the above
query how to reference a child table to the parent table using the
references keyword.
Creating a table from another table :-
Now, we will see how to create a table from another table – i.e, it
duplicates all the records and the characterstics of another table.
The SQL query for it is as follows,
Thus we can see that we have created another table temp from the
table dept.
Thus, we can see that the table temp has copied the structure of the
table dept. Here, we must observe that temp copies all the columns,
rows and NOT NULL constraints only from the table dept. It never
copies PK, FK, Check constraints.
Thus, when in the interview somebody asks you “I have a table
which has about 1million records. How do I duplicate it into
another table without using Insert keyword and without
inserting it individually all the records into the duplicated
table ?
Answer is - Use the above query of creating a table from
another table and explain it.
TRUNCATE
It removes all the data permanently, but the structure of the table
remains as it is.
Ex – SQL > TRUNCATE TABLE test ;
DROP
Rename Table:
It renames a table.
Syntax:
Rename table_name to new_table_name
ALTER
- this query alters / changes the structure of the table (i.e, - adding
columns, removing columns, renaming columns etc ).
INSERT:
Insert into table_Name
Values(v1,v2,v2…)
Or
Insert into table_Name (column1,column2,…)
Values (v1,v1,….)
Note:
This is how we insert values into a table. All characters and alpha-
numeric characters(ex – 10023sdf78) must be enclosed in single
quotes (‘ ‘ ) and each value must be separated by comma. Also we
must be careful in entering the data without violating the primary
key, foreign key , unique constraints.
During an abnormal exit – i.e, shutdown or if the SQL window
is closed by mouse click – then all the DML’s will be rolled back
automatically.
DELETE
It deletes one / some / all the records.
Ex: Delete from table
TCL (Transaction Control Language)
ROLLBACK
COMMIT
Committing after rollback & vice versa will not have any effect
Data transaction Language(DTL)
SavePoint
Rollback to savepoint
Grant:
grant select on emp to hr;
Login as HR
Revoke:
Login as Scott
revoke select on emp from hr;
Login as HR
Difference Between Oracle and SQL Server
We have divided our 1NF table into two tables viz. Table 1 and Table2.
Table 1 contains member information. Table 2 contains information on
movies rented.
3NF Rules
Rule 1- Be in 2NF
Rule 2- Has no transitive functional dependencies
To move our 2NF table into 3NF we again need to need divide our
table.
Conversion Functions:
Conversion function s are used to convert one data type into
another data type
There are two type of conversion Functions
1. Implicit conversion Function
Ex: Select 10+’20’ from dual;
NVL Functions:
1> NVL(arg1,arg2)
• If agr1 is null it returns arg2
• If arg1 is not null then it returns itself
Ex:
If more than only one column should be added at one time, respective add clauses need to be
separated by colons. A table constraint can be added to a table using
alter table <table> add (<table constraint>);
The syntax of the command for modifying a column
is