Sqlqueries IMP Interview Questions-2
Sqlqueries IMP Interview Questions-2
where clause filter the data before gruop by clause and having clause clause
Query to print out the individual total number of duplicate row in sql.
Answer ANS:
#1
SELECT department_id,COUNT(department_id)
AS "Occurrences"
FROM departments
GROUP BY department_id
HAVING ( COUNT(department_id) > 1 )
How can I create a table from another table without copying any
values from the old table?
Answer In oracle
#8 Create table newtablename as select * from
oldtablename where 1=2
Primary key:
It is an unique identifier, it wont allow null value, in a table there will be
only one column as primary key.
Composite key:
It same as Primary key but combination of more that one column.
Write a query to find the name of employees those who have joined on
Monday.(based on column hire_date)
(select distinct esal from test_emp order by esal desc) where rownum <= N)
(OR)
write a query to delete similar records in different tables with same structure?
DELETE FROM table1 WHERE(col1,col2,..) IN (SELECT col1,col2,.. FROM
table2 where condition)
DECLARE
TABLENAME_TMP TABLE;
CURSOR C1 IS
SELECT M.TABLE_NAME
FROM USER_TAB_COLS M
WHERE M.COLUMN_NAME LIKE 'EMPNO';
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO TABLENAME_TMP;
WHEN C1%NOTFOUND THEN EXIT;
WHERE A.EMPNO>=B.EMPNO);
ENDLOOP;
CLOSE C1;
END DUP;
what are the different types of joins?
1)Self Join
2)Equi join (or)Inner Join
2.1)Non-equi Join
3)Outer Join
3.1) Left-Outer Join
3.2) Right-Outer Join
3.3) Full-Outer Join
We can only copy the structure of the table and not the constraints. In this
way only NOT NULL constraint specified on any column of the OLDTABLE
will automatically get copied into the NEWTABLE but other constraint will
have to be created manually.
When we can declare a column as Unique and Not Null both at the same
time. What is the use pf Primary Key then?
The concept of adding an unique key and not null constraint to a column as
well as adding as unique index to it , you will assume to get the benefits of
adding an primary key to that column.
But use it for the purpose of referential integrity will not allow to do so.
That's what PK is so useful. You will use it for normalization purpose.
How do you get all records from 2 tables. Which join do you use?
Using FULLOUTER JOIN?
triggers are invoked implicitly , while stored procedures are invoked explicitly.
What is the fastest way of accessing a row in a table?
Answer
The fastest way to access row is by rowid.
#1
I have one table :EID,Depid,ename,sal I want to have max(sal) in each
department.?
write a query to dispaly those name who is more than one in student table?
example- in a student table sandeep kumar comes 4 times, rakesh kumar
comes 2 times, ajit kumar comes 1 times so query will display sandeep
kumar and rakesh kumar single times?
Answer SELECT COUNT(NAME_FIELD_NAME)AS
#1 NOMBER_OF_OCCURENCE FROM
STUDENT WHERE
NUMBER_OF_OCCURANCE >1;
display list of all users from ur data base. what is the query?
i deleted 4 records form the table.after i have applied commit .now i want to
get back those records.how?
Flashback table feature is available from Oracle 9i onwards only. Before that
deleted records once committed cannot be rolled back. As far as Oracle 9i
onwards the solution specified by Bipin Maurya is correct. But i would like to
add something. For using FLASHBACK TABLE the user must be granted
privilege for the same. But there is another way out.
This will bring the table to the point in time specified by timestamp.
how many outer joins are used in a single sql query? is there any limitations for using
of outer joins?
Answer
ANS:
#1
Only one outer join is possible for a single query & it can be either left
outer join or right outer join or full outer join.
We can't use two outer joins for a single query.
Flash Table
Restore the table employees_demo to its state 1 minute prior to the current
system time:
If another employees table has been created in the hr schema, use the
RENAME TO clause to rename the retrieved table:
FLASHBACK TABLE employees TO BEFORE DROP RENAME TO
employees_old;
If you know that the employees table has been dropped multiple times, and
you wish to retrieve the oldest version, query the USER_RECYLEBIN table to
determine the system-generated name, and then use that name in the
FLASHBACK TABLE statement. (System-generated names in your database
will differ from those shown here.)
SELECT object_name, droptime FROM user_recyclebin WHERE
original_name = 'employees';
Display full details for the creditor/s who has received the single
largest payment. Do not use a table join or set operator anywhere in
your query.
Answer SELECT MAX(SALARY) FROM (SELECT
#4 FIRST_NAME,SALARY,FROM EMP
ORDER BY SALARY DESC) WHERE
ROWNUM<=1 GROUP BY
FIRST_NAME,SALARY;
SQLTuning Advisor
SQLAccess Advisor
In oracle 10g :
( OR)
select * from employees where rowid = (select max(rowid) from employees)or
rowid =(select min(rowid)from employees)
functions:
1.The parameters are input values and output values
2.The functions will return a value
3.The functions will be called with in sql
Procedures:
1.The parameters are input values and output values
2.The procedures will not return any value
3.The procedures will not be called with in sql
There are two tables (T1, T2) with different rows. Find the output of
query. Select count(*) from T1,T2.
Answer
yes multiply both tables rows
#2
how to find Nth row ?(N th Record)
select * from emp where rownum<=N minus select * from emp where
rownum<N
(or)
select * from emp e1 where N = (select count(rowid)from emp e2
where e1.rowid >= e2.rowid);
View is nothing but the virtual table made from few columns of the base table
to get faster retrieval and fetch of the data. Hence when you update any view
the column which you updating is get updated, and the column basically
belongs to the base table. hence answer is IT WILL UPDATE BASE TABLE.
(OR)
for max
select distinct a.sal from emp a where &N= (select count(distinct b.sal) from
emp b where b.sal>=a.sal)
select distinct a.sal from emp a where &N= (select count(distinct b.sal) from
emp b where b.sal<=a.sal)
select * from (select * from emp order by esal desc) where rownum<=N;
primary key is used to identify a row and it doesnt allow null values. It
avoids duplication of rows. Primary key will not allow "Null values" and
"Duplicate values. Primary key is unique, primary key is not NULL .
foreign key is NULL, foreign key reference as Primary key in another table.
Whereas foreign key refers to a column or combination of columns included
in the definition of referential integrity.
Foreign key will allow "Null values" and "Duplicate values and it refers to a
primary key in anoter table.
Re: What is the difference between column level constraints and table
level constraints?
Answer column level constraints contain all types of
#2 constraints (like, not null,primary key,foregin
key,unique).but table level except not null
constraint its supports all constraints.
Triggers are the database objects (Like Procedures) which will be executed by
the Database itself and cannot be excuted by the user explicitly. The trigger
can be written to execute while inserting/ updating/ deleting a row.
Yes i am agree with all three answers but there are different Scenarios. You
cannot call a procedure in which dml ,ddl statement or transaction controlling
statement is used. You can all a procedure in which only select statement is
used. Please check if you dont have trust.
Re: There is a table1 with records (1,2,3,4,5,6) and table2 with records
(4,5,6,7,8,9).write a query so as to get the result as 1,2,3,4,5,6,7,8,9
Answer select * from table1 union select * from table2
#1
-- Union will give distinct value of both tables
Trigger created.
Trigger dropped.
What are the factors you will check for the performane optimization for a
database query?
But indexes can hit the performance for insert queries. So before giving an
insert query, better to remove the index and then to recreate the index.
2)
1.In the select statement give which ever the columns you need
don't give select * from
2.Do not use count()function
3.use indexes and drop indexes regularly it B tree structure we are not going
to drop means it will take time for creating indexes it self.
4.when joining the tables use the id's(integer type)not string
5.Sometimes you may have more than one subqueries in your main query.
Try to minimize the number of subquery block in your query.
6.Use operator EXISTS, IN and table joins appropriately in your query.
a) Usually IN has the slowest performance.
b) IN is efficient when most of the filter criteria is in the sub-query.
c) EXISTS is efficient when most of the filter criteria is in the main query.
7.Use EXISTS instead of DISTINCT when using joins which involves tables
having one-to-many relationship.
8.Try to use UNION ALL in place of UNION.
9.Avoid the 'like' and not like in where clause.
10.Use non-column expression on one side of the query because it will be
processed earlier.
11.To store large binary objects, first place them in the file system and add the
file path in the database.
3)
try to use function based indexes and use it when needed..
it will not be used unnecessarily.
use clustering concept while creating table it will make you join operation fast
if more join operation u r going to perform on the tables
The system hides certain details of how data is stored and created and
maintained Complexity should be hidden from database users.this is data
abstraction.
How will you fine tune a stored procedure or what are the steps that should
be taken to fine tune or optimize a stored procedure?
For exaple:
var EmpName;
EmpName= Request.form ("EmpName");
var sql = "select * from Employee where
EmpName= '" +
EmpName+ "'";
Let?s say you have 100,000 records and you want to delete 95,000 at a
time and keep only 5 thousand. But in local memory you don?t have
enough space for 95,000 records. What do you do in this case? How do
you delete without any problem with time and performance?
Answer First select the 5000 records u want to keep..
#1 put it in
memory.. then delete the entire table.. and
then put this
5000 record table in place
For example:
create table Table1
( T1_Id integer not null primary key
, T1_Data varchar(9) not null
)
create table Table2
( T2_Id integer not null primary key
, T2_Data varchar(37) not null
, foreign key (T2_Id) references Table1 (T1_Id)
)
Correlated subquery runs once for each row selected by the outer query. It
contains a reference to a value from the row selected by the outer query.
Nested subquery runs only once for the entire nesting (outer) query. It does
not contain any reference to the outer query row.
Correlated Subquery:
select e1.empname e1.basicsal e1.deptno from emp e1 where e1.basicsal =
(select max(basicsal) from emp e2 where e2.deptno = e1.deptno)
Nested Subquery:
select empname basicsal deptno from emp where (deptno, basicsal) in (select
deptno max(basicsal) from emp group by deptno)
In oracle way -
---------------
First normal form (1NF or Minimal Form) is a normal form used in database
normalization. A relational database table that adheres to 1NF is one that is
free of repeating groups.Second normal form (2NF) is a normal form used in
database normalization,where a table that is in first
normal form (1NF) must meet additional criteria if it is to qualify for second
normal form. Specifically:a 1NF table is in 2NF if and only if none of its non-
prime attributes are functionally dependent on a part (proper subset) of a
candidate key. (A non-prime attribute is one that does not
belong to any candidate key.)
Second normal form further removes the duplicate data: i.e. Meet the
requirements of the first form of normalalization. Create relationships
between new tables through foreign keys.
truncate
drop
it deletes the records as well as structure of the table too
we cannot rollback the records
we can flashback the table from the version 9x
it is ddl
delete
it deletes the only records which are we mention in the where clause or whole
records
it is dml
we can rollback it
What is the order in which the SQL query is executed? list them in order.?
(2)
At runtime the compiler first takes the table name from where the data is to
be retrieved (FROM <tablename>), then it checks for the condition (Where
<condition>) then it selects the values to me displayed as o/p
sql job is scheduling the work into server and it will automatically run and
finish the job for this we have to set the time.what is the use of the job is
1) it check the database automatically
2)take a back up of database
for this job we have to start the Sqlserver agent and give the date and time for
this particular job
IF i write before / after insert / update trigger and i do rollback what will
happen?
How to get the count of distinct records. Please give me the query?
Answer select count(distinct(columnname)) from
#6 tablename
what is Normalization?
Answer Normalizatiin is the scientific method of
#6 breaking down
complex table sturcture into simple table
structure by
using certain rules.using this method you can
reduce
redundency in a table and eliminate the
problem of
inconsisteny and disk space usage
if UNION ALL and Natural Join does the same operation and are same?
Both are not same why because in UNION ALL operator can retrive the total
number of records from the table and NATUAL JOIN OR EQUI JOIN
operator retrive the rows which are condition must be the same and datatype
of the column names must be same
emp table
dept table
deptid deptno
1 10
2 20
if i join this two tables
(empid = deptid)
how to write the query to select the rows are in the order of either 1,3,5,7... or
2,4,6,8,.?
For 1,3,5,7...
select * from emp where (rowid,1) in (select rowid,mod(rownum,2) from
emp);
For 2,4,6,8,...
select * from emp where (rowid,0) in (select rowid,mod(rownum,2) from
emp);
stored procedure:
--create a sample performance tuning procedure
Cursor is an Database object and retrive the rows from database row by
row ,And it is maily use for ot reduce the network traffic.
it contains 5 features
1.DECLARE the Cursor
2.OPEN the cusrsor
3.FETCH the cursor
4.CLOSE the cursor
5.DEALLOCATE the cursor
Data integrity allows to define certain data quality requirements that the data
in the database needs to meet. If a user tries to insert data that doesn't meet
these requirements, Oracle will not allow so.
Constraint types
There are five integrity constraints in Oracle.
Not Null
A column in a table can be specified not null. It's notpossible to insert a null in
such a column. The default is null. So, in the following create table statement,
a null can be inserted into the column named c.
Primary Key
Primary keys can explicitely be named. The following create table statement
creates a table with a primary key whose name is pk_name.
create table ri_primary_key_1
(
a number,
b number,
c number,
constraint pk_name primary key (a, b)
);
Foreign Key
A foreign key constraint (also called referential integrity constraint) on a
column ensures that the value in that column is found in the primary key of
another table.If a table has a foreign key that references a table, that
referenced table can be dropped with a drop table cascade
constraints.It is not possible to establish a foreign key on a global temporary
table. If tried, Oracle issues a ORA-14455:
attempt to create referential integrity constraint on temporary table.Check A
check constraint allows to state a minimum requirement for the value in a
column. If more complicated requirements are
desired, an insert trigger must be used.
The following table allows only numbers that are between 0 and 100 in the
column a;
create table ri_check_1 (
a number check (a between 0 and 100),
b number
);
It is also possible to state a check constraint that check the value of more than
one column. The following example makes sure that the value of begin_ is
smaller than the value of end_.
ANY - used in case of relational queries to compare result with any of the key.
SQL - select custID from orders where regionID != "E" and discount > any
(select discount from orders where regionID = "E" and discount > 3)
ALL - used in case of relational queries to compare result with all of the keys.
SQL - select custID from orders where regionID != "E" and discount > all
(select discount from orders where regionID = "E" and discount > 3)
ANY-It will compare with any value that has been returned by the parameter;
select * from emp where salary > any(select salary from emp where
deptno=10)
the salary will be compared with any value that has been returned by the
subquery.
ALL-It will compare with max/min value that has been returned by the
subquery;
select * from emp where salary > all(select salary from emp where deptno=10)
the salary will be compared with the longest value that has been returned by
the subquery.
WHAT IS INDEXING?
I have one Excel file with 80,000 Records. Now I need to load that whole file
into Oracle Database with same columns in Excel sheet . How can i do that?
CHAR should be used for storing fix length character strings. VARCHAR
behaves exactly the same as VARCHAR2. However, this type should not be
used as it is reserved for future usage.
VARCHAR2 is used to store variable length character strings. The string
value's length will be stored on disk with the value itself. VARCHAR can
store up to 2000 bytes of characters while VARCHAR2 can store up to 4000
bytes of characters.
If we declare datatype as VARCHAR then it will occupy space for NULL
values, In case of VARCHAR2 datatype it will not occupy any space.
(1)
SELECT floor((date1-date2)*24)
|| ' HOURS ' ||
mod(floor((date1-date2)*24*60),60)
|| ' MINUTES ' ||
mod(floor((date1-date2)*24*60*60),60)
|| ' SECS ' time_difference
FROM dates;
(2)
(3)
9. What is an ERD
An ERD is an Entity-Relationship-Diagram. It is used to show the entities and
relationships for a database logical model.
Joins:
A Join is the process of combining data from two or more tables. The DBMS
takes all combinations of rows from the given tables.
Cross Join:
A Cross Join is the Cartesian product or the result of all possible combinations
of the rows from each of the tables involved in the join operation. This occurs
when, no specific Join conditions (filters) are specified. For eg: there are 3
tables A,B and C with 10,20 and 30 number of rows respectively. So a
cartesian production would happen in the below scenario,
These are ANSI Joins which are used for portability. You can use this
in almost all Standard Databases like Oracle, Microsoft SQL Server etc.
Self Join:
For Eg: If you need to get all employees and their managers, then you could
do a self join.
PS: This is just to show an example for Self Join. The results may not be
accurate.
Inner joins returns only the rows from the cross product that meets the join
condition/s.
Returns data only from those records which matches the condition
EMP.DEPTNO = DEPT.DEPTNO, from both tables
Outer Join:
For eg:
Returns all records from EMP and only those records from DEPT which
matches the condition EMP.DEPTNO = DEPT.DEPTNO
Returns all records from table B and only those matching with the join
operation from Table A (just the reverse of left outer join)
For eg:
Returns all records from DEPT and only those records from EMP which
matches the condition EMP.DEPTNO = DEPT.DEPTNO
SQL Injection
1. Overview
2. Introduction
SQL injection refers to the attack on the applications which have Oracle as
back end database. The activity to inject SQL and PL/SQL code through an
application is SQL injection. It is a serious vulnerability and may lead to fatal
consequences. An unauthorized attacker may get full database access by
inputting bad input through application which may lead to leakage of
important data.
The SQL query below gets the password of an input user from the USERS
table.
Code sql:
SELECT USERNAME, PASSWORD FROM USERS WHERE USERNAME =
'CLUB'
Developers are ignorant that their above query can be misused to an extent
that it can list login names and passwords, which is relevant and crucial
information for an organization. An invader can give input as
Code : ''OR 1=1
which can retrieve all login and password.
Code sql:
SELECT USERNAME, PASSWORD
FROM USERS
WHERE USERNAME = ''
OR 1=1
In the above SQL, WHERE clause has two filter conditions. First condition
yields FALSE while the second condition gives TRUE output. Since both are
combined using OR logical operator, the combination gives TRUE and query
retrieves all the login names and their passwords.
Like the above technique, SQL code can be exploited in multiple ways.
Dynamic SQL and User/Definer right preserved subprograms are most prone
to SQL injections.
Depending on the impact of SQL Injection, it can be divided into two major
categories.
First Order Attack Second Order Attack
Bad string Input (using quote and Performing an alternate activity to an
concatenation operator) ongoing system activity
A procedure P_GET_SAL was created to get the salary of input Employee Id.
Code sql:
A malicious input can be given in below ways to inject the SQL. Illustration is
as below.
Code sql:
SQL> EXEC P_GET_SAL(KING);
Employee KING draws 4500
Code sql:
SQL> EXEC P_GET_SAL('KING'' UNION SELECT ENAME, SALARY FROM
EMPLOYEE WHERE 1=1');
Employee KING draws 4500
Employee ALLEN draws 1200
Employee MIKE draws 3400
Employee KATE draws 2300
Employee PAUL draws 6400
Employee TOMY draws 2700
Employee JENNY draws 6200
Employee JAKES draws 4600
Several strategies can be adopted to safeguard the SQL code and eradicate the
impacts of SQL injection in applications. Some of them are listed below.
A sample ER model
Above two statements are enough to create an ER model for the data.
3. Normalization
Data Normalization is the activity used to organize data in the database to
sweep out redundant data and ensure sensible relationships. A normalized
database not only ensures logical storage of data but also upgrades
performance and data interactivity. A database can be normalized up to
below degrees.
Second Normal Form Once the data passes the 1NF, the attributes which
are same in multiple rows can be moved to separate tables. 2NF talks about
creating relationship between the two tables where one table contains the
primary key data, while the other one contains the repetitive data for each key
value.
In the below example, Customer and Items share relationship. The entity
Item contains non key attributes like Item Mfg date and Item Prod date,
which are not dependent on the Order Number Key. Instead, they describe a
property of an Item.
The normalization levels proposed by E.F. Codd are considered as standard
techniques. Additionally, Boyce Codd Normal Form (BCNF) addresses
dependencies between attributes and Candidate key. Candidate key is the
column which is eligible to be a primary key. If candidate key becomes
primary key, then 1NF, 2NF, and 3NF apply to BCNF classification also.
Below are the additional normalization levels.
In addition to above fundamentals, below are some terms which are required
to be familiar with during DB design process. Below are few of them
1. Entity and Relationship The objects whose information is required to be
stored is called as Entity. It represents a thing or an event. An entity has
differentiable characteristics and optionally, it can have descriptive
characteristics too.
An entity can be associated to another entity through a defined Relationship.
In a statement Oracle is best DBMS in the world, the terms Oracle and
DBMS are entities while is best defines the relationship between the two.
For example, Employee is an entity.
Advantages of ER Model
Easy to understand
Eases the physical design from Logical design
Disadvantages
The ER model is focused on Data and not on process or methodology.