You are on page 1of 11

SQL 6. What are Tables and Fields?

LEFT (OUTER) JOIN: Retrieves all the records


A table is an organized collection of data stored from the left and the matched records from the
in the form of rows and columns. right table.
1. What is Database?
The columns in a table are called fields while SELECT *
A database is an organized collection of data.
the rows can be referred to as records. FROM Table_A A
LEFT JOIN Table_B B
2. What is DBMS?
7. What are Constraints in SQL? ON A.col = B.col;
DBMS stands for Database Management
To maintain integrity in the table we use
System. DBMS is a system software
constraints RIGHT (OUTER) JOIN: Retrieves all the
responsible for the creation, retrieval, updation
NOT NULL - It will not allow null data. records from the right and the matched records
and management of the database.
UNIQUE - It allows only unique values into from the left table.
fields. SELECT *
3. What is RDBMS? How is it different from
INDEX - It provides faster retrieval of records. FROM Table_A A
DBMS?
PRIMARY KEY - It allows null and as well as it RIGHT JOIN Table_B B
RDBMS stands for Relational Database
is unique. ON A.col = B.col;
Management System.
FOREIGN KEY - It points to the primary key
RDBMS stores data in the form of a collection
from another table. 9. What is an Index? Explain its different
of tables and relations can be defined between
CHECK - Verifies that all values in a field types.
the common fields of these tables
satisfy a condition. Indexes provides faster retrieval of records.
DEFAULT - Automatically assigns a default
4. What is SQL?
value if no value has been UNIQUE AND NON-UNIQUE INDEX:
SQL stands for Structured Query Language. It
Unique indexes ensuring that no two rows of
is the standard language for relational database
8. What is a Join? List its different types. data in a table have identical key values
management systems.
The SQL Join clause is used to combine CREATE UNIQUE INDEX myIndex
records from two or more tables. ON students (enroll_no);
5. What is the difference between SQL and
Non-unique indexes, on the other hand, are not
MySQL?
(INNER) JOIN: Retrieves records that have used to enforce constraints on the tables
SQL is a standard language for retrieving and
matching values in both tables.
manipulating structured databases.
SELECT * CLUSTERED AND NON-CLUSTERED INDEX:
On the contrary, MySQL is a relational
FROM Table_A Clustered index modifies the way records are
database management system, like SQL
JOIN Table_B; stored in a database based on the indexed
Server, Oracle that is used to manage SQL
SELECT * column.
databases.
FROM Table_A A non-clustered index creates a separate entity
INNER JOIN Table_B; within the table which references the original
table.
10. What is Data Integrity? different from WHERE, since the WHERE Finally use the DEALLOCATE statement to
It defines integrity constraints to enforce clause cannot filter aggregated records. delete the cursor definition and release the
business rules on the data when it is entered associated resources.
into a database. 14. What are UNION, MINUS and
INTERSECT commands? 16. What is trigger ?
11. What is a Query? The UNION operator combines and returns the A trigger is a special type of stored procedure
A query is a request for data or information result-set retrieved by two or more SELECT that automatically runs when an event occurs in
from a database. A database query can be statements. the database server. DML triggers run when a
either a select query or an action query. The MINUS operator in SQL is used to remove user tries to modify data through a data
duplicates from the result-set manipulation language (DML) event. DML
12. What is a Subquery? What are its types? The INTERSECT clause in SQL combines the events are INSERT, UPDATE, or DELETE
A subquery is a query within another query, result-set fetched by the two SELECT statements
also known as a nested query or inner query statements where records from one match the
CORRELATED AND NON-CORRELATED. other 17. What are Entities and Relationships?
A correlated subquery cannot be considered as ENTITY: An entity can be a real-world object,
an independent query, but it can refer to the 15. What is Cursor? How to use a Cursor? either tangible or intangible, that can be easily
column in a table. A database cursor is a control structure that identifiable. For example, in a college
A non-correlated subquery can be considered allows for the traversal of records in a database, students, etc.
as an independent query database.
They can be viewed as a pointer to one row in RELATIONSHIPS: Relations or links between
13. What are some common clauses used a set of rows. entities that have something to do with each
with SELECT query in SQL? other. For example - The employee's table in a
WHERE: It is used to filter records that are Working with SQL Cursor: company's database can be associated with
necessary, based on specific conditions. DECLARE a cursor after any variable the salary table in the same database.
declaration. The cursor declaration must One-to-One
ORDER BY: It used to sort the records based always be associated with a SELECT One-to-Many
on some field(s) in ascending (ASC) or Statement. Many-to-One
descending order (DESC); Open cursor to initialize the result set. The Many-to-Many
OPEN statement must be called before fetching
GROUP BY: It is used to group records with rows from the result set 18. What is an Alias in SQL?
identical data and also summarized results FETCH statement to retrieve and move to the It is a temporary name assigned to the table or
from the database. next row in the result set. table column.
Call the CLOSE statement to deactivate the A table alias is also called a correlation name.
HAVING: It is used to filter records in cursor. Using the AS keyword is always a good
combination with the GROUP BY clause. It is practice.
19. What is a View? DELETE FROM Candidates LAST() - Fetches the last element in a
A view in SQL is a virtual table based on the WHERE CandidateId > 1000; collection of values.
result-set of an SQL statement. Note: All aggregate functions described above
A view just like a real table TRUNCATE command is used to delete all the ignore NULL values except for the COUNT
SIMPLE VIEW: Simple view has been created rows from the table and free the space function.
on only a single containing the table.
table. TRUNCATE TABLE Candidates; A scalar function returns a single value based
COMPLEX VIEW: Views which are created on the input value. Following are the widely
using more than 1 table which has joins DROP command is used to remove an object used SQL scalar functions:
clauses are known as complex views. from the database. If you drop a table, all the
rows in the table are deleted and the table LEN() - Calculates the total length of the given
20. What is Normalization? structure is removed from the database. field (column).
Normalization is process of organizing data into DROP TABLE Candidates; UCASE() - Converts a collection of string
related table. values to uppercase characters.
22. What are Aggregate and Scalar LCASE() - Converts a collection of string values
1NF(First Normalization Form) functions? to lowercase characters.
A single row cannot hold multiple values. Aggregate function : It performs operations on MID() - Extracts substrings from a collection of
a collection of values to return a single scalar string values in a table.
2NF(Second Normalization Form) value. Aggregate functions are often used with CONCAT() - Concatenates two or more strings.
Table has to be in 1NF(First Normalization the GROUP BY and HAVING clauses of the RAND() - Generates a random collection of
Form). SELECT statement. Following are the widely numbers of a given length.
Table should not contain partial dependency used SQL aggregate functions: ROUND() - Calculates the round-off integer
( Table having composite primary key i.e., value for a numeric field (or decimal point
partial dependency) AVG() - Calculates the mean of a collection of values).
values. NOW() - Returns the current date & time.
3NF(Third Normalization Form) COUNT() - Counts the total number of records FORMAT() - Sets the format to display a
It is used to reduce data duplication. in a specific table or view. collection of values.
Table should not contain transitive MIN() - Calculates the minimum of a collection
dependency. of values. 23. What is User-defined function? What are
A->B, B->C (Functional dependency) MAX() - Calculates the maximum of a collection its various types?
A->C (Transitive dependency) of values. The user-defined functions in SQL are like
SUM() - Calculates the sum of a collection of functions in any other programming language
21. What are the TRUNCATE, DELETE and values. that accept parameters, perform complex
DROP statements? FIRST() - Fetches the first element in a calculations, and return a value
DELETE statement is used to delete rows from collection of values.
a table.
SCALAR FUNCTION: It return a single scalar Search a student in your database with first MATCHING PATTERNS FOR A SPECIFIC
value. name beginning with the letter K: LENGTH
TABLE-VALUED FUNCTIONS: It limits the length and position of the matched
INLINE: returns a table data type based on a SELECT * results. For example -
single select statement. FROM students
MULTI-STATEMENT: returns a tabular result- WHERE first_name LIKE 'K%' SELECT * /* Matches first names with three or
set more letters */
OMITTING THE PATTERNS USING THE NOT FROM students
24. What is a Stored Procedure? KEYWORD WHERE first_name LIKE '___%'
A stored procedure is a prepared SQL code This query returns all students whose first
that you can save, so the code can be reused name does not begin with K. SELECT * /* Matches first names with exactly
over and over again. four characters */
A stored procedure is a subroutine available to FROM students
applications that access a relational database SELECT * WHERE first_name LIKE '____'
management system (RDBMS) FROM students
The sole disadvantage of stored procedure is WHERE first_name NOT LIKE 'K%'
that it can be executed nowhere except in the 27. Explain About DDL Statements of SQL?
database and occupies more memory in the MATCHING A PATTERN ANYWHERE USING DDL – DDL stands for Data Definition
database server. But it also provides a sense of THE % WILDCARD TWICE Language:
security and functionality Search for a student in the database where CREATE Creates a new table, a view of a
he/she has a K in his/her first name. table, or other object in database.
25. What is a Recursive Stored Procedure? ALTER Modifies an existing database object,
A stored procedure that calls itself until a SELECT * such as a table.
boundary condition is reached, is called a FROM students DROP Deletes an entire table, a view of a table
recursive stored procedure. WHERE first_name LIKE '%Q%' or other object in the database.

26. What is Pattern Matching in SQL? USING THE _ WILDCARD TO MATCH 28. What is DML in SQL. Explain DML
This kind of SQL query uses wildcards to match PATTERN AT A SPECIFIC POSITION Statements in Details?
a string pattern, rather than writing the exact This query fetches all students with letter K at DML stands for Data Manipulation Language:
word. The LIKE operator is used in conjunction the third position in their first name. INSERT Creates a record
with SQL Wildcards to fetch the required UPDATE Modifies records
information. SELECT * DELETE Deletes records
FROM students
USING THE % WILDCARD TO PERFORM A WHERE first_name LIKE '__K%'
SIMPLE SEARCH
ADVANCED SQL 4. PERFORMANCE TESTING means either all operations are executed or
ENVIRONMENT: none of them.
On this environment the performance tester An example can be bank transaction from one
1. What is the latest version of Oracle?
tests all account to another account. Either both debit
Oracle 19c.
performance related issues on this and credit operations must be executed or
.
environment. This environment contains very none of them.
2. What are advantages of Oracle 19c?
huge data and performance tester will try to ACID (Atomicity, Consistency, Isolation,
It provides the highest level of release stability
break the system using that big data. Durability) is a set of properties that guarantee
and longest time frame for support and bug
5. PRODUCTION ENVIRONMENT: that database transactions are processed
fixes.
On this Environment actual user works and reliably.
Following are some advantages of Oracle 19c :
uses the software
a. It reduces the complexity of database
8. What is SQL Profiler?
b. It is highly reliable and secure database
4. What is mean by Sequence in database? SQL Profiler is a graphical tool that allows
c. It reduces the operational cost
Use the CREATE SEQUENCE statement to system administrators to monitor events in an
d. Self Driving database
create a sequence, which is a database object instance of
from which multiple users may generate unique Microsoft SQL Server. You can capture and
3. What are different database
integers. You can use sequences to save data about each event to a file or SQL
Environments used in any project?
automatically generate primary key values. Server table to analyze later. For example, you
The Project to project database environment
can monitor a production environment to see
varies. But the following is basic environment
5. What is Null in SQL? which stored procedures are hampering
structure used for projects.
A NULL value in a table is a value in a field that performance by executing too slowly
1. DEVELOPMENT ENVIRONMENT:
appears to be blank, which means a field with a
In Development Environment all developer
NULL value is a field with no value. 9. What is Self Join?
works.
This is a particular case when one table joins to
2. TEST ENVIRONMENT:
6. What is not null constraint? itself, with one or two aliases to avoid
After development is done the code is migrated
By default, a table column can hold NULL confusion. The common example is when
to Test Environment. Testing team is working
values. The NOT NULL constraint enforces a company have a hierarchal reporting structure
on Test environment and execute black box as
column to NOT accept NULL values. This whereby one member of staff reports to
well as white box test cases on this
means that you cannot insert a new record, or another.
Environment. Sometimes System Integration
update a record without adding a value to this
Testing (SIT) is also done on this Environment.
field. 10. What is Cross Join?
3. UAT ENVIRONMENT:
A cross join that does not have a WHERE
UAT stands for User Acceptance Testing. On
7. What is a transaction? What are ACID clause produces the Cartesian product of the
this Environment the Customer side testers
properties? tables involved in the join. The common
tests the software and executes. User
A Database Transaction is a set of database example is when company wants to combine
Acceptance Test Cases.
operations that must be treated as whole,
each product with a pricing table to analyze 16. What are the differences between OLTP 19. How to know which index a table is
each product at each price. and OLAP? using?
OLTP stands for Online Transaction SELECT table_name,index_name FROM
11. What is De-normalization? Processing, is a class of software applications user_constraints
De-normalization is the process of attempting capable of supporting transaction-oriented
to optimize the performance of a database by programs. 20. What is substring?
adding OLAP stands for Online Analytical Processing,
redundant data. a class of software programs that are
. characterized by the relatively low frequency of
12. How to represent comments in oracle? online transactions.
SINGLE LINE COMMENT: Two dashes (–)
before beginning of the line 17. What is Collation? What are the different
MULTILINE COMMENT/BLOCK COMMENT: types of Collation Sensitivity?
When user wants to comment multiple line /* */ Collation refers to a set of rules that determine
operators are used. how data is sorted and compared.
Below are the different types of collation
13. What is raw datatype? sensitivity:
Raw datatype is used to store values in binary CASE SENSITIVITY: A and a are treated
data format. differently.
There are 2 types of RAW datatype. ACCENT SENSITIVITY: a and á are treated
RAW: Raw datatype is variable length datatype differently.
like varchar2 but basically it only stores data in KANA SENSITIVITY: Japanese kana
1 ‘s and 0’s means binary data format. characters Hiragana and Katakana are treated
LONG RAW: Long raw datatype is used to differently.
store graphics, sound documents. WIDTH SENSITIVITY: Same character
represented in single-byte (half-width) and
14. What is ROWID & ROWNUM? double-byte (full-width) are treated differently.
ROWID is nothing but the physical address
given to that row which is in hexadecimal 18. How to create empty tables with the
format. same structure as another table?
ROWNUM is nothing but the logical sequence By fetching the records of one table into a new
given to the row of that column. table using the INTO operator

15. Which virtual table does a trigger use?


Inserted and Deleted.
Where Rownum =1; Order By a.salary desc;

Complex SQL Queries 5. What is the Query to fetch last record ALTERNATIVE SOLUTION:
from the table? Select min(salary)
Select * From Employee From(Select distinct salary
1. Query to find Second Highest Salary of
Where Rowid= select max(Rowid) From emp
Employee?
From Employee; Order By salary desc)
Select distinct Salary From Employee e1
Where rownum<=3;
Where 2=Select count(distinct Salary)
6. What is Query to display first 5 Records
From Employee e2
from Employee table? 10. How to Display Odd rows in Employee
Where e1.salary<=e2.salary;
Select * From Employee table?
Where Rownum <= 5; Select * From(Select rownum
ALTERNATIVE SOLUTION :
As rno,E.*
Select min(salary)
7. What is Query to display last 5 Records From Employee E)
From(select distinct salary
from Employee table? Where Mod(rno,2)=1;
From emp
Select * From Employee e
Order By salary desc)
Where rownum <=5 11. How to Display Even rows in Employee
Where rownum<=2;
UNION table?
Select * from (Select * from Employee e Select * From(Select rownum
2. Query to find duplicate rows in table?
Order By rowid desc) As rno,E.*
Select * From Employee a
Where rownum <=5; From Employee)
Where rowid <>
where Mod(rno,2)=0;
( select max(rowid)
8. What is Query to display Nth Record from
From Employee b
Employee table? 12. How to fetch 3rd highest salary using
Where
Select * from ( select a.*, rownum rnum Rank Function?
a.Employee_num=b.Employee_num);
From (YOUR_QUERY_GOES_HERE select * from (Select Dense_Rank()
— including the Order By ) a Over ( Order By salary desc)
3. How to fetch monthly Salary of Employee
Where rownum <= N_ROWS ) As Rnk,E.*
if annual salary is given?
Where rnum >= N_ROWS From Employee E)
Select Employee_name,Salary/12
Where Rnk=3;
As ‘Monthly Salary’
9. How to get 3 Highest salaries records
From employee;
from Employee table? 13. How Can I create table with same
Select Distinct salary From employee a structure of Employee table?
4. What is the Query to fetch first record
Where 3 >= (Select count(distinct salary) Create table Employee_1
from Employee table?
From employee b As Select * from Employee
Select * From Employee
Where a.salary <=b.salary) Where 1=2;
19. How to get distinct records from the Select e.employee_name, m.employee name
14. Display first 50% records from Employee table without using distinct keyword. From Employee e, Employee m
table? Select * From Employee a Where e.Employee_id=m.Manager_id;
Select rownum, e.* Where rowid = (select max(rowid)
From emp e From Employee b 25. Display the name of employees who
Where rownum<=(Select count(*)/2 Where have joined in 2016 and salary is greater
From emp); a.Employee_no=b.Employee_no); than 10000?
Select name From Employee
15. Display last 50% records from Employee 20. Select all records from Employee table Where Hire_Date
table? whose name is ‘Amit’ and ‘Pradnya’ Like ‘2016%’
Select rownum,E.* from Employee E Select * From Employee And salary>10000;
MINUS Where Name
Select rownum,E.* from Employee E In(‘Amit’, ’Pradnya’); 26. How to display following using query?
Where rownum<=(Select count(*)/2) *
From Employee); 21. Select all records from Employee table **
where name not in ‘Amit’ and ‘Pradnya’ ***
16. How Can I create table with same Select * From Employee We cannot use dual table to display output
structure with data of Employee table? Where name given above. To display output use any table. I
Create table Employee1 Not In (‘Amit’ ,’Pradnya’); am using Student table.
As select *
From Employee; 22. How to fetch all the records from SELECT lpad (‘*’, ROWNUM,’*’)
Employee whose joining year is 2017? FROM Student
17. How do i fetch only common records Oracle: WHERE ROWNUM <4;
between 2 tables? Select * from Employee
Select * from Employee; Where To_char(Joining_date, ’YYYY’)=’2017′; 27. How to add the email validation using
INTERSECT only one query?
Select * from Employee1; 23. What is SQL Query to find maximum SELECT Email
salary of each department? FROM Employee
18. Find Query to get information of Select Dept_id,max(salary) Where NOT REGEXP_LIKE(Email,
Employee where Employee is not assigned From Employee ‘[A-Z0-9._%+-]+@[A-Z0-
to the department ? Group By Dept_id; 9.-]+\.[A-Z]{2,4}’, ‘i’);
Select * From Employee
Where Dept_no 24. How Do you find all Employees with its 28. How to display 1 to 100 Numbers with
Not In(Select Department_no managers? query?
`From Employee); (Consider there is manager id also in Employee Select level from dual
table): Connect By level <=100;
29. How to remove duplicate rows from
table?
STEP 1: Selecting Duplicate rows from table

Select rollno FROM Student


WHERE ROWID <>(Select max (rowid)
from Student b
where rollno=b.rollno);

STEP 2: Delete duplicate rows

Delete FROM Student


WHERE ROWID <>(Select max (rowid)
From Student b
Where rollno=b.rollno);

30. How to find count of duplicate rows?


Select rollno, count (rollno) From Student
Group by rollno
Having count (rollno)>1
Order by count (rollno) desc;

31. How to find all details about Constraint?


1.Select * From User_constraints;
OR
2.Select * From User_cons_columns;
PL SQL 2. What are different cursor attributes? Triggers are database objects with specific
There are following cursor attributes : conditions.
1.%Found
1. What is cursor in PL SQL ?
2.%Not Found Examples of Trigger :
Cursor is a buffer area which is used to process
3.%Isopen 1)Audit data modifications.
multiple records and also record by record tabs.
4.%Rowcount 2)Log events transparently.
There are 2 types of cursors :
3)Enforce complex business rules.
1. IMPLICIT CURSOR : Implicit cursor is a
3. What is ref cursor? Why it is used? 4)Maintain replica tables
buffer area which has been defined and
As the name suggested ref cursor is a variable 5)Derive column values
controlled by oracle internally. Implicit cursor
which will point to the address or reference of 6)Implement Complex security authorizations.
will process single record at a time.
the cursor. Ref cursor is variable not cursor but
example :
that variable points to cursor. 6. What is %ROWTYPE ? Explain this with
declare
There are 2 type of ref cursors : example.
v_Ename varchar2(100);
1.Strong Ref cursor %ROWTYPE is cursor attribute which is used
begin
2.Weak Ref cursor to define the record of the field.Each field
select ename into V_Ename from Employee
assumes it own datatype and %ROWTYPE is
where
4. How to write Cursor with for loop? used to define the specific record type.
empno=101;
Cursor declares %ROWTYPE as loop index example :
dbms_output.put_line(V_Ename );
implicitly. It then opens a cursor, gets rows of
end;
values from the active set in fields of the record CREATE OR REPLACE PROCEDURE
The above cursor is implicit cursor where all the
and shuts when all records are processed. P_Employee_Information
operations are defined by oracle engine
Means while using the for loop user don’t need IS
internally like declaring the cursor, fetching
to Open the cursor and fetch the values from CURSOR Emp_Cur IS SELECT
values from the cursor and close cursor.
cursor or close cursor explicitly. Employee_name,
Employee_Number FROM emp;
2. EXPLICIT CURSOR : Explicit cursor is a
In For loop all cursor operations done implicitly variable1 Emp_Cur %ROWTYPE; ---This is
cursor which is defined by user to process set
Real Example: cursor variable
of records. For multiple records user needs to
FOR Sample_cursor IN C1 LOOP name
use explicit cursor. Explicit cursor operations
Total_Salary=Total_Salary + Appraisals; BEGIN
are done by
END LOOP; OPEN Emp_Cur ;
the user. There are following 4 operations
LOOP
needs to be done by user :
5. What is Database Trigger? What is real FETCH Emp_Cur INTO variable1;
1.Declare cursor
use of trigger? EXIT WHEN Emp_Cur %Notfound; ---When
2.Open cursor
PL SQL procedure which is used to trigger cursor
3.Fetch all records from the cursor
specific event on specific condition is known as DBMS_OUTPUT.PUT_LINE( variable1.Employ
4.Close cursor.
database triggers. ee_name || '
works in department ' 1.The work done in a transition is undone as if
|| myvar.Employee_Number); it was never issued.
END LOOP; 2.All locks acquired by transaction are
CLOSE Emp_Cur ; released.
END
SAVEPOINT :
7.What is Raise_Application_Error? It undoes all the work done by the user in a
When user wants to insert Error message then transaction.
user needs to use the Raise_Application_Error With SAVEPOINT, only part of transaction can
procedure. Raise_Application_Error is the be
system defined procedure of package named Undone.
DBMS_STANDARD.
9. What is mutating error?
Syntax : It occurs when a trigger tries to update a row
Raise_Application_Error(Error_Code,Error_Me that it is currently using. It is fixed by using
ssage); views or temporary tables, so database selects
one and updates the other.
Example :
Raise_Application_Error (-20343, 10. What is difference between Anonymous
‘The balance is too low.’); block and subprogram?
ANONYMOUS BLOCK :
8. What is commit? RollBack? Savepoint? Anonymous blocks are programs or unnamed
COMMIT : block
When user commits the data after transaction which is used to check some functionality and
that changes which are not stored in database.
are permanent changes.
1.Other users can see the data changes made SUBPROGRAMS :
by the transaction. Subprograms are stored blocks which are
2.The locks acquired by the transaction are stored in to database. Subprograms are
released. compiled at runtime.
3.The work done by the transaction becomes
permanent
.
ROLLBACK :
When transaction become wrong user can
rollback the data.

You might also like