[go: up one dir, main page]

0% found this document useful (0 votes)
18 views40 pages

Mock Test 8

Uploaded by

praneshp1003.sse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views40 pages

Mock Test 8

Uploaded by

praneshp1003.sse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Unattempted

NF-1

•Each record in the table must be unique

NF-2

•NF-1+

•Find the unique keys and assign Primary keys. Direct dependent redundant data taken
into new table.

NF-3

•NF-2+

•Transitive dependency redundant data taken into new Table


& need to input the substitution variable every time as it clean-up after the call

&& once input is provided, subsequent call variable is taken from memory
WITH t
AS
(
SELECT ‘KING‘ ename, ‘king@mgmail.com‘ email_id FROM dual
UNION ALL
SELECT ‘SCOTT‘ ename, ‘scott_tiger@gmail.com‘ email_id FROM dual
UNION ALL
SELECT ‘FORD‘ ename, ‘ford@gmail.com‘ email_id FROM dual
)
SELECT * FROM t WHERE email_id LIKE ‘%\_%‘ ESCAPE ‘\‘
/
ENAME EMAIL_ID
—— ———–
SCOTT scott_tiger@gmail.com

_ and “%” are special characters used inside LIKE clause. So to find string with _ or %
we need to add ESCAPE in search query

Example:

SELECT * FROM t WHERE email_id LIKE ‘%!_%‘ ESCAPE ‘!‘


SELECT * FROM t WHERE str LIKE ‘%!%%‘ ESCAPE ‘!‘
SELECT * FROM t WHERE str LIKE ‘%\%%‘ ESCAPE ‘\‘
Unattempted

–Constraint created at column level


CREATE TABLE DEPT
(DEPTNO NUMBER(2) CONSTRAINT PK_DEPT PRIMARY KEY,
DNAME VARCHAR2(14) ,
LOC VARCHAR2(13)
)
/
Table created

–Multiple Foreign keys constraint created at column level


CREATE TABLE EMP
(EMPNO NUMBER(4) CONSTRAINT PK_EMP PRIMARY KEY,
ENAME VARCHAR2(20) NOT NULL,
JOB VARCHAR2(9),
EMAIL_ID VARCHAR2(30) CONSTRAINT UK_EMP UNIQUE,
MGR NUMBER(4),
HIREDATE DATE,
SAL NUMBER(7,2),
DEPTNO NUMBER(2) CONSTRAINT FK_DEPTNO REFERENCES DEPT,
DEPTNO2 NUMBER(2) CONSTRAINT FK_DEPTNO2 REFERENCES DEPT
)
/
Table created

ALTER TABLE EMP DROP constraint PK_EMP


/
Table altered
ALTER TABLE EMP DROP constraint FK_DEPTNO
/
Table altered
ALTER TABLE EMP ADD constraint PK_EMP PRIMARY KEY (empno)
/
Table altered
ALTER TABLE emp ADD CONSTRAINT FK_DEPTNO FOREIGN KEY (deptno)
REFERENCES dept(deptno);
/
Table altered
UPDATE emp e
SET e.sal= e.sal * 1.1
WHERE e.deptno = (SELECT deptno
FROM dept d
WHERE e.deptno = d.deptno AND d.loc IN (‘NEW YORK‘,‘DALLAS‘)
)
/
4 rows updated
Character

CHAR – Fixed-length character max data size 2000 bytes

VARCHAR2 – Variable-length character max data size 4000 bytes

CLOB – Variable-length character data and max size 4 GBs

LONG – Variable-length character data.


Note: savepoint A never established in the session because it is removed after the
commit.
SELECT TO_CHAR (1720.253, ‘$99G999D00‘) output FROM DUAL
/
output
————
$1,720.25

SELECT TO_CHAR (1720.253, ‘$9,999V99‘) FROM DUAL


/
output
————
$172,025

SELECT TO_CHAR (1720.253, ‘$0G000D00‘) FROM DUAL


/
output
————
$1,720.25

SELECT TO_CHAR (1720.253, ‘$99,999D99‘) FROM DUAL


/
ORA-01481: invalid number format model
SELECT TO_CHAR (1720.253, ‘$99G999D99‘) FROM DUAL
/
output
————
$1,720.25

SELECT prod_id, prod_desc, price


FROM product WHERE (prod_cat_id = 1 AND prod_cat_id = 5) AND year_of_man =
2019
/
no rows selected
Note: prod_cat_id = 1 AND prod_cat_id = 5 will always return false as a product can be
either of one category (1 OR 5 not both)
The correct answer is C. ON DELETE CASCADE is already set, and the keyword FROM
is optional in a DELETE statement.

SELECT customer_id, ‘ ‘ , first_name, ‘ ‘ , last_name “CUSTID FIRSTNAME LASTNAME



FROM customers
/
CUSTOMER_ID ‘‘ FIRST_NAME ‘‘ CUSTID FIRSTNAME LASTNAME
———– — ————- — ————————-

1 Debra Burks
2 Kasha Todd
3 Tameka Fisher
4 Daryl Spence
5 Charolette Rice
6 Lyndsey Bean
7 Latasha Hays
SELECT e1.empno,
e1.ename,
e1.sal,
e2.avg_sal
FROM emp e1 WHERE e1.sal >
(SELECT AVG(e2.sal) AS avg_sal
FROM emp e2
WHERE e1.deptno = e2.deptno
) ORDER BY e1.sal DESC
/
ERROR at line 4:
ORA-00904: “E2″.”AVG_SAL”: invalid identifier
VARCHAR2 -> minimum size is VARCHAR2(1);

LONG -> There cannot be more than one column of LONG datatype.

TIMESTAMP -> Can store Date + Time upto nano seconds

CHAR -> CHAR blank-padded to the maximum defined column width

BLOB -> Binary Large Objects

CLOB -> Character Large Objects


displaying a date in a nondefault format
SELECT to_char(sysdate,‘DDth, MON-YYYY‘) output FROM dual
/
OUTPUT
————
03RD, MAR-2021
finding the number of characters in an expression
SELECT LENGTH(‘Oracle‘) len FROM dual
/
LEN
—-
6
substituting a character string in a text expression with a specified string
SELECT REPLACE(‘Welcome To Sequel‘, ‘Sequel‘,‘SQL‘) new_str FROM dual
/
new_str
—-
Welcome To SQL
combining more than two columns or expressions into a single column in the output
SELECT CONCAT(‘HARRY‘,‘POTTER‘) join_str FROM dual
/
join_str
———–
HARRYPOTTER
Note: Here single CONCAT built-in can process only 2 columns not more than 2
columns.
Database Management System = Database + Management System

Database: Only Data

Management System: Which manages data & supports below things

1. Data Storing

2. Data retrieval

3. Data modification

4. Access control of Data


SELECT * FROM emp ORDER BY SAL DESC
/
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
—– —– ——— —– ——— —– —— ———
7839 KING PRESIDENT – 17-NOV-81 5000 – 10
7902 FORD ANALYST 7566 03-DEC-81 3000 – 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 – 20
7566 JONES MANAGER 7839 02-APR-81 2975 – 20
7698 BLAKE MANAGER 7839 01-MAY-81 2850 – 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 – 10
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7934 MILLER CLERK 7782 23-JAN-82 1300 – 10
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 – 20
7900 JAMES CLERK 7698 03-DEC-81 950 – 30
7369 SMITH CLERK 7902 17-DEC-80 800 – 20

SELECT * FROM emp ORDER BY SAL DESC


OFFSET 2 ROWS
FETCH NEXT 3 ROW ONLY
/
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
—— ——- —— —— ——– —– —- ———
7902 FORD ANALYST 7566 03-DEC-81 3000 – 20
7566 JONES MANAGER 7839 02-APR-81 2975 – 20
7698 BLAKE MANAGER 7839 01-MAY-81 2850 – 30
SCOTT@XE> SELECT SIGN(-125), SIGN(0), SIGN(100)FROM dual
/
SIGN(-125) SIGN(0) SIGN(100)
———- ———- ———-
-1 0 1
SIGN(Number)

If number < 0, then the SIGN function returns -1. if number = 0, then the SIGN function
returns 0. If number > 0, then the SIGN function returns 1.

SELECT * FROM emp ORDER BY sal DESC FETCH NEXT 2 ROWS WITH TIES
/
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
—— —— ——- —— ——— —- —– ———-
7839 KING PRESIDENT – 17-NOV-81 5000 – 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 – 20
7902 FORD ANALYST 7566 03-DEC-81 3000 – 20

Syntax

[ OFFSET offset { ROW | ROWS } ]


[ FETCH { FIRST | NEXT } [ { rowcount | percent PERCENT } ] { ROW | ROWS } { ONLY
| WITH TIES } ]
SCOTT@XE > SELECT * FROM emp WHERE ename = ‘&var_name‘
2/
old 1: SELECT * FROM emp WHERE ename = ‘&var_name‘
new 1: SELECT * FROM emp WHERE ename = ‘SMITH‘

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


——– ———- ——- —- ———- —– —— ——-
7369 SMITH CLERK 7902 10-MAR-1990 800 – 20
Substitution variable can be used in a SQL statement by prefixing either & or &&

SCOTT@XE> SELECT CEIL(-10.5), (10), CEIL(10.5) FROM dual;

CEIL(-10.5) (10) CEIL(10.5)


———– ———- ———-
-10 10 11
CEIL(num)

The value used to determine the largest integer value that is equal to or greater than the
number.

SELECT TRANSLATE(‘I am a World Citizen‘,‘abcABC‘,‘xyzXYZ‘)


FROM dual
/
STR
———–
I xm x World Zitizen
TRANSLATE does character by character replace as per sequence of characters
provided.

WITH t
AS
(
SELECT TO_TIMESTAMP(‘06-09-2020 09:15:25.245374‘,‘DD-MM-YYYY
HH:MI:SS.FF‘) outputTime FROM dual
)SELECT EXTRACT(YEAR FROM t.outputTime) time_year,
EXTRACT(MONTH FROM t.outputTime) time_month,
EXTRACT(DAY FROM t.outputTime) time_day,
EXTRACT(HOUR FROM t.outputTime) time_hour,
EXTRACT(MINUTE FROM t.outputTime) time_Minute,
EXTRACT(SECOND FROM t.outputTime) time_Second
FROM t
/
TIME_YEAR TIME_MONTH TIME_DAY TIME_HOUR TIME_MINUTE TIME_SECOND
———- ————– ———- ———– ———- —————
2020 9 6 9 15 25.245374

SELECT NULLIF (‘apple‘, ‘apple‘) val1,


NULLIF (‘apple‘, ‘orange‘) val2
FROM dual
/
VAL1 VAL2
—– —–
apple
TRUNC(Num, n)

ROUND(Num, n)

IF n is 0 it works on decimal point.

-1 means works on digit before decimal means here 5 => TRUNC(315.451, -1) = 310

-2 means works on 2 digit before decimal means here 15 => TRUNC(315.451, -2) =
300

-3 means works on 3 digit before decimal means here 315 => TRUNC(315.451, -3) = 0

SELECT TRUNC(315.451,-3), TRUNC(315.451,-1),


TRUNC(315.451,0), TRUNC(315.451,1)
FROM dual
/
TRUNC(315.451,-3) TRUNC(315.451,-1) TRUNC(315.451,0) TRUNC(315.451,1)
—————– —————– —————– ——————
0 310 315 315.4
SELECT LAST_DAY(TO_DATE(‘14-12-2019‘, ‘DD-MM-YYYY‘)) Output
FROM dual
/
OUTPUT
———-
12/31/2019

LAST_DAY(date) takes input a date and displays the last date of the month

Oracle recommends that you specify explicit conversions, rather than rely on implicit or
automatic conversions,

for these reasons:

•SQL statements are easier to understand when you use explicit data type conversion
functions.
•Implicit data type conversion can have a negative impact on performance

Example:

SELECT salary + ‘10‘ FROM employee; –Implicit conversion


SELECT salary + TO_NUMBER(‘10‘) FROM employee; –Explicit conversion

SELECT SUM(e.sal)
FROM emp e GROUP BY deptno HAVING e.deptno IN (10, 20) ORDER BY SUM(e.sal)
DESC
/
SUM(E.SAL)
————–
10875
8750

Group function syntax

SELECT exp1, exp2, … expn,


agg_function (aggr_exp)
FROM tables [WHERE conditions]
GROUP BY exp1, exp2, … expn
[Having conditions];
For each record in outer query, the Inner query executes based upon conditions

DECODE ( , , ,
,,

);

Equivalent to

IF ( = ) THEN

ELIF ( = ) THEN

ELSE
END IF;
SELECT DECODE(40, 10, ‘ACCOUNTING‘, 20, ‘RESEARCH‘,30, ‘SALES‘, ‘OTHERS‘ )
dept_desc
FROM dual
/
dept_desc
———-
OTHERS
SELECT A.VAL A_VAL, B.VAL B_VAL FROM A
LEFT OUTER JOIN B ON A.ID = B.ID
/
A_VAL B_VAL
—– ———–
20 20
30 30
10
LEFT OUTER JOIN (LEFT JOIN)

It would return the all records from table1 and only those records from table2 that
intersect with table1

Self-joins

Joining the same table with itself.


–Ask DBA to create a directory
CREATE DIRECTORY test_dir as ‘D:\Temp‘;
–Ask DBA to Grant READ and WRITE access on the directory to user
SQL> GRANT READ,WRITE ON directory test_dir TO SCOTT;

CREATE TABLE languages(


language_id NUMBER(3),
language_name VARCHAR2(30)
) ORGANIZATION EXTERNAL(
TYPE oracle_loader
DEFAULT DIRECTORY test_dir
ACCESS PARAMETERS
(FIELDS TERMINATED BY ‘,‘)
LOCATION (‘languages.csv‘)
);
SELECT language_id, language_name FROM languages;
–private synonym: Masking the name ie- emp is masked and given an another name
private_emp
CREATE SYNONYM private_emp FOR emp
/
synonym created
–public synonym: Masking the schema and name of the object ie- scott & emp is
masked and given an another name public_emp
CREATE PUBLIC SYNONYM public_emp FOR scott.emp
/
synonym create

Object privilege

A schema object privilege is a privilege or right to perform a particular action on a


specific schema object

Example:

GRANT SELECT on emp;


GRANT SELECT on sequence_name;

We can find all the object level privileges granted to a user or a role
SQL> SELECT grantee, table_name, privilege FROM user_tab_privs
/
GRANTEE TABLE_NAME PRIVILEGE
————- ————- ——————
ROLE_ADMIN DEPT DELETE
ROLE_ADMIN DEPT INSERT
SCOTT EMPLOYEES SELECT
ROLE_ADMIN EMP SELECT

–Note there there is no joins so it is a cartesion Join.


SELECT e.empno , e.ename, d.loc FROM emp e, dept d;
SELECT count(*) FROM v_emp WHERE loc = ‘DALLAS‘
/
8

SELECT count(*) FROM emp WHERE deptno = 20 –deptno of DALLAS = 20


/
2
In Emp table number of employee working in DALLAS are only 2 records. But in view
v_emp the employees working in DALLAS are 8 records so emp table data is not key
preserved in the view. That means each row of the view not exactly representing the
same row in emp table so if we try to delete from the view, it will throw below error.
DELETE FROM v_emp WHERE loc = ‘DALLAS‘;
ORA-01752: cannot delete from view without exactly one key-preserved table

SCOTT@XE> GRANT SELECT, INSERT, UPDATE, DELETE , DEBUG, ALTER on


EMP to USER1;
Grant succeeded.
Note: SELECT ALL on EMP contains GRANT SELECT, INSERT, UPDATE, DELETE ,
DEBUG, ALTER, QUERY REWRITE & FLASHBACK

How to check it

–First grant ALL to a user.


CONN scott/tiger
GRANT ALL on emp to user1;

CONN user1/user1
SELECT *
FROM user_tab_privs WHERE table_name = ‘EMP‘;
conn scott/tiger
–Find grants attached to a role
SELECT * FROM user_tab_privs WHERE grantee = ‘ROLE_CLERK‘
/
GRANTEE OWNER TABLE_NAME GRANTOR PRIVILEGE
———— —— ————- ——– ———
ROLE_CLERK SCOTT FRUITS SCOTT SELECT
ROLE_CLERK SCOTT EMP SCOTT SELECT
ROLE_CLERK SCOTT DEPT SCOTT SELECT

GRANT SELECT, INSERT ON emp to user1;

Conn user1/user1
SELECT * FROM user_tab_privs WHERE owner = ‘SCOTT‘
/
GRANTEE OWNER TABLE_NAME GRANTOR PRIVILEGE
——– —— ———- ——— ——
USER1 SCOTT EMP SCOTT INSERT
USER1 SCOTT EMP SCOTT SELECT
USER_TAB_PRIVS can provide privileges granted to a user and role
CREATE TABLE Emp_Exp
(
Empl_id VARCHAR2(10),
Empl_nm VARCHAR2(30),
Joining_date DATE,
Experince INTERVAL YEAR TO MONTH
)
/
Table created

CREATE TABLE Job_run_status


(
Job_id VARCHAR2(10),
Job_nm VARCHAR2(30),
Job_begin TIMESTAMP,
Job_end TIMESTAMP,
Dur INTERVAL DAY TO SECOND
)
/
Table created
System privilege:

A system privilege is the right to perform a particular action, or to perform an action on


any schema objects of a particular type

Example:

GRANT create table to scott


/
GRANT create sequence to scott
/

Note: that here scott can create tables and sequences.

Data dictionary to find the system privileges granted to a role or user

SQL> SELECT * FROM user_sys_privs;

USERNAME PRIVILEGE ADM COM INH


———– ———– — — —-
SCOTT CREATE SESSION NO NO NO
SCOTT CREATE TRIGGER NO NO NO
SCOTT CREATE ROLE NO NO NO
SCOTT CREATE VIEW NO NO NO

Note:

user_sys_privs – for system privileges

user_tab_privs – for object privileges

You might also like