Download SQL 1. What are the types of SQL statement? Data Manipulation

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Concurrency control wikipedia , lookup

Oracle Database wikipedia , lookup

Database wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Ingres (database) wikipedia , lookup

Functional Database Model wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Relational algebra wikipedia , lookup

Clusterpoint wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

SQL wikipedia , lookup

PL/SQL wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Relational model wikipedia , lookup

Database model wikipedia , lookup

Join (SQL) wikipedia , lookup

Transcript
SQL
1. What are the types of SQL statement?
Data Manipulation Language
Data Definiton language
transaction control
session control
system control
select - data retrieval
insert, update, delete, merge - DML
Create, alter, drop, rename, truncate - DDL
Commit, rollback, savepoint - transaction control
grant, revoke - DCL
2. What is a transaction
A collection of DML statements that form a logical unit of work is called a transaction
Transaction is a set of DML statements end up once a commit or rollback statements are
encountered
3: What is difference between TRUNCATE & DELETE
Both commands accomplish identical tasks (removing all data from a table), but TRUNCATE is
much faster.
truncate = delete+commit -so we cant roll back
delete = delete- so it can be rolled back
Delete - delete deletes the records from table it can be rollbacked also you can give the
where condiition to it.
Truncate - delete all records from table There is no rollback it always commit without
givening the commit
Truncate: Drop all object's statistics and marks like High Water Mark, free extents and leave
the object really empty with the first extent.
Delete: You can keep object's statistics and all allocated space.
4: What is a join
A join is a query that combines rows from two or more tables, views, or materialized views.
Oracle performs a join whenever multiple tables appear in the query's FROM clause. The
query's select list can select any columns from any of these tables. If any two of these tables
have a column name in common, then you must qualify all references to these columns
throughout the query with table names to avoid ambiguity.
Most join queries contain WHERE clause conditions that compare two columns, each from a
different table. Such a condition is called a join condition. To execute a join, Oracle combines
pairs of rows, each containing one row from each table, for which the join condition evaluates
to TRUE. The columns in the join conditions need not also appear in the select list.
To execute a join of three or more tables, Oracle first joins two of the tables based on the join
conditions comparing their columns and then joins the result to another table based on join
conditions containing columns of the joined tables and the new table. Oracle continues this
process until all tables are joined into the result. The optimizer determines the order in which
Oracle joins tables based on the join conditions, indexes on the tables, and, in the case of the
cost-based optimization approach, statistics for the tables.
5: Explain the different types of joins
Basically Joins are used to get result from two or more tables and there are two types of joins
inner join and outer join
Inner join : a join of two or more tables which omits the blank rows while checking
Outer join is subcatogorised in to left outer join and right outer join. Which includes blank
rows in specifed side if condition satisfies.
shiva
1
SQL
Apart from these there are
Natural join : cartisian product
Equi join : which includes = operator in condition
NonEqui join : All conditional joins which doesn't uses = in there conditions.
6: What is the sub-query
A subquery is a SELECT statement that is written inside another SQL statement (which is
often, but does not have to be, another SELECT). To distinguish the subquery (or inner query)
from its enclosing query (or outer query), it must be enclosed within parentheses. Here is an
example:
SELECT * FROM clients WHERE clno IN -- outer query
(SELECT clno FROM firms WHERE city = 'leduc'); -- inner query
7: What is correlated sub-query
A correlated sub-query is a subquery that references the value/s from the main query.
example :
SELECT colA, colB
FROM tableA
WHERE colB < ( SELECT max(colX)
FROM tableB
WHERE tableB.colY = tableA.colA)
Oracle executes correlated subquery for each record from of main query .. hence these types
of queries have greater impact on performance and must be avoided
8: Explain CONNECT BY PRIOR
The start with .. connect by clause can be used to select data that has a hierarchical
relationship (usually some sort of parent->child (boss->employee or thing->parts).
9: Difference between SUBSTR and INSTR
INSTR (String1,String2(n,(m)), INSTR returns the position of the mth occurrence of the
string 2 in
string1. The search begins from nth position of string1.
SUBSTR (String1 n,m), SUBSTR returns a character string of size m in string1, starting from
nth postion of string1.
10: Explain UNION, MINUS, UNION ALL and INTERSECT
UNION - the values of the first query are returned with the values of the second query
eliminating duplicates.
MINUS - the values of the first query are returned with duplicates values of the second query
removed from the first query.
UNION ALL - the values of both queries are returned including all duplicates
INTERSECT - only the duplicate values are returned from both queries.
11: What is ROWID
ROWID is the psedo columns indicate the stored location of the data physically in the
database.
12: What is the fastest way of accessing a row in a table
Using rowid
A ROWID is created by Oracle for each new row in every table, it is a pseudo column that has
a value for every row in a table. The ROWID gives us the physical address of a row and is the
fastest way to access any row.
The ROWID contains 3 bits of information, they are :The block within the database file.
Row # within the block.
Database file ID.
An example could be :000088C9.0191.0002
shiva
2
SQL
The ROWID has three important uses, it is :The fastest path to any row.
A way of speeding the COMMIT process in application code.
Unique identifiers of any given row.
13: What is an integrity constraint
An integrity constraint is a rule that restricts the values in a database. There are six types:
A NOT NULL constraint prohibits a database value from being null.
A unique constraint prohibits multiple rows from having the same value in the same column or
combination of columns but allows some values to be null.
A primary key constraint combines a NOT NULL constraint and a unique constraint in a single
declaration. That is, it prohibits multiple rows from having the same value in the same column
or combination of columns and prohibits values from being null.
A foreign key constraint requires values in one table to match values in another table.
A check constraint requires a value in the database to comply with a specified condition.
A REF column by definition references an object in another object type or in a relational table.
A REF constraint lets you further describe the relationship between the REF column and the
object it references.
14: What is referential integrity constraint
It refers to the integrity between master and detail table. If the information from the master
table is deleted then the corresponding record from the detail table should also get deleted as
this information has no meaning without master table
15: What is the usage of SAVEPOINTS
SAVEPOINTS are used to subdivide a transaction into smaller parts. It enables rolling back
part of a transaction. Maximum of five save points are allowed.
Savepoints are the temporary bookmarks. it is possible to rollback up to the named savepoint.
By utilizing savepoints, you are able to rollback to a given point in your processing.
An example of this would be:
...
COMMIT;
INSERT
UPDATE
SAVEPOINT A
DELETE
UPDATE
INSERT
SAVEPOINT B
INSERT
INSERT
DELETE
SAVEPOINT C
ROLLBACK TO SAVEPOINT B
I only lost the two inserts and delete. Had I not placed savepoints in my processing and used
a rollback, I would have lost my entire transaction back to the last good commit.
16: What is ON DELETE CASCADE
when the user deletes a record in the master table , all the corresponding records in the detail
table along with the records in the master table will be deleted.
shiva
3
SQL
17: What are the data types allowed in a table
binary
Bigint
bit
Char
datetime
decimal
Float
image
Int
Money
nchar
Ntext
nvarchar
Numeric
Real
smalldatetime
smallint
smallmoney
sql_variant
sysname
text
timestamp
tinyint
varbinary
varchar
uniqueidentifier
these are the data types used in sql table
18: What is difference between CHAR and VARCHAR2
char is a fixed length charater data type.
varchar is a variable length length character data type.
Char will store null values even if the data inside the field is less than the specified length.
Storage will be same as specified length.
Varchar2 will store null values, if data is less than specified length, storage will be that much
only.
A varchar2 datatype, when stored in a database table, uses only the space
allocated to it. If you have a varchar2(1999) and put 50 bytes in the table, we
will use 52 bytes (leading length byte).
A char datatype, when stored in a database table, always uses the maximum length
and is blank padded. If you have char(1999) and put 50 bytes into it, it will
consume 2001 bytes (leading length field is present on char's as well).
In the database -- a CHAR is a VARCHAR that is blank padded to its maximum
length.
19.Question: How many LONG columns are allowed in a table
Answer: Only one LONG columns is allowed. It is not possible to use LONG column in WHERE
or ORDER BY clause.
20. What are the pre-requisites to modify datatype of a column and to add a column
with NOT NULL constraint
1) to modify datatype of a column - ???
2) to add a column with NOT NULL constraint - the table must have 0 rows
21. Where the integrity constraints are stored in data dictionary
The user_constraints data dictionary table stores the details of integrity constraints details
Constraints are found under the USER_CONSTRAINTS table.
22. How will you activate/deactivate integrity constraints
Using enable/disable clause along with Alter command, we can activate/deactive constraints.
For example:
Alter table Empolyee disable/Enable constraint pk_EmpNumer
23. Question: What is a database link
scott@8i> create database link ora8idev
2 connect to scott
3 identified by tiger
4 using 'ora8idev'
5 /
Database link created.
scott@8i> select * from dual@ora8idev;
shiva
4
SQL
24. How to access the current value and next value from a sequence
example to use the sequence.currval and sequence.nextval
create sequence seq_name
start with 1
minvalue 1
maxvalue 999
increment by 1
nocycle
insert into table_name (sno,name) values (seqname.nextval,'abc');
select seqname.currval from dual
25: What are the advantages of VIEW
Views are useful for providing a horizontal or vertical subset of data from a table (possibly for
security reasons) ; for hiding the complexity of a query; for ensuring that exactly the same
SQL is used throughout your application; and in n-tier applications to retrieve supplementary
information about an item from a related table.
26.What is CYCLE/NO CYCLE in a Sequence
Answer:
When you create a sequence with CYCLE option, you are saying that when the sequence
reaches its MAXVALUE, it will start over at the MINVALUE. This is not wise if using the
sequence for primary key creation.
When you create a sequence with NOCYCLE option, you are saying that when the sequence
reaches its MAXVALUE, it will NOT start over at the MINVALUE. This option is safest if using
the sequence for primary key creation. When the sequence reaches its MAXVALUE an oracle
error is thrown.
27: Can a view be updated/inserted/deleted
There are restrictions since a view can join multiple tables and have functions and groupings it
may not be possible to update a view. Simple views on one table can definately be updateable
If Yes - under what conditions
an Insert,Update,delete can be done through views is
1. inserts/updates/deletes done only in one base table at a time
2. primary key columns should be part of view
3. columns which are going to be updated must be part of vew def.
4. it shouldn't voielet the constraints
5. The query of the view shoud not consist of any aggregate funtion
6. The query shoud not consist of any subquery
7 And the other option is we can use the instead of trigger to update the Table/s based up on
the dml operation issued over the view. so that the modified data will be reflected in the view.
28. If a view on a single base table is manipulated will the changes be reflected on
the base table
Yes
29: How do I eliminate the duplicate rows
DELETE TableName WHERE rowid NOT IN ( SELECT MIN(rowid) FROM TableName GROUP BY
ColumnName );
30: How do I display row number with records
select rownum, table_name.* from table_name;
shiva
5
SQL
31: Display the records between two range I know the nvl function only allows the
same data type(ie. number or char or date Nvl(comm, 0)), if commission is null then
the text “Not Applicable” want to display, instead of blank space. How do I write the
query
you can use the decode function for the above requirement. Please find the query as
below:
select ename,decode(nvl(comm,0),0,'Not Applicable',comm) from scott.emp;
32: Explicit Cursor attributes
%IS OPEN,%FOUND,%NOT FOUND,%ROW COUNT
33: Implicit Cursor attributes
SQL%FOUND,SQL%NOT FOUND, SQL%IS OPEN, SQL%ROW COUNT
34: To view installed Oracle version information
select * from v$version;
35: Find out nth highest salary from emp table
select sal from emp e where n-1=(select count(distinct sal) from emp where sal>e.sal);
36: Display the number value in Words
select sal, (to_char(to_date(sal,'j'), 'jsp')) from emp;
37: Display Odd/ Even number of records
Odd number of records:
select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp);
1
3
5
Even number of records:
select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp)
2
4
6
38: Which date function returns number value
“months_between”
This date function takes 2 valid dates and returns number of months in between them.
39: Any three PL/SQL Exceptions
NO_DATA_FOUND
WHEN_OTHERS
TOO_MANY_ROWS
invalid_cursor,
cursor_not_open
40: Other way to replace query result null value with a text
NVL or Decode
41: What are the more common pseudo-columns
Answer:
ROWNUM, ROWID, LEVEL
42: What is the output of SIGN function
SIGN (a): Returns 1 if a is positive or if a is 0, and -1 if a is less than 0.
shiva
6
SQL
43:How to drop the index
Drop Index Indexname
44: How to drop the column in a table
There are 2 ways of doing it :
alter table"table name" drop column "column name";
This drops the column immediately. However if there is huge data and you would like to
postpone the task of dropping the columns you can make the columns unused and drop the
unused columns during the weekend or less peak activity time.
45.Subquery vs Join
The main difference betwen subquery and join is
subquery is faster when we have to retrieve data from large number of tables.Because it
becomes tedious to join more tables.
join is faster to retrieve data from database when we have less number of tables
46: What is meant by SORTING and GROUPING
For sorting we use order by clause in select statement. This is used to sort data in ascending
order or descending order.
To group data based on perticulr column we use groupby clause.
Both are used to get distinct values.
47:: The use of HAVING , WHERE and GROUPBY in one SQL
where" filters data before grouping
"Having" filters data after grouping
48: What is a transaction ?
A transaction either commits (i.e. all its actions happen), or it aborts (i.e. all its actions are
undone). This all-or-nothing quality makes for a simple programming model.
Transactions also meets the ACID test: Atomic, Consistent, Isolation, and Durable
49: What is difference between CHAR and VARCHAR2 ? What is the maximum SIZE
allowed for each type ?
Answer: CHAR pads blank spaces to the maximum length. VARCHAR2 does not pad blank
spaces. For CHAR it is 255 and 2000 for VARCHAR2.
50: What is the use of TNSNAME.ORA and LISTENER.ORA files
Answer: tnsnames.ora is used to connect to the remote db. To get the connection listener.ora
should be configured at the server and it should be up and running.
51: what is the diffrence between and constraints and triggers
Constraints are used to maintain the integrity and atomicity of database .in other words it can be said they
are used to prevent invalid data entry . the main 5 constraints are
NOT NULL,PRIMARY KEY,FOREIGN KEY,UNIQUE KEY and CHECK
Triggers are bascically stored procedures which automaticallly fired when any insert,update or delete is
issued on table
52: what is the difference between primary key, unique key, sorrougate key?
Primary Key: A column in a table whose values uniquely identify the rows in the table. A primary key value
cannot be NULL.
Unique Key: Unique Keys are used to uniquely identify each row in an Oracle table. There can be one and
only one row for each unique key value.
Surrogate Key: A system generated key with no business value. Usually implemented with database
generated sequences.
shiva
7
SQL
53.what is normalization? what is the advantage of normalization (briefly)
The process of separating data into distinct, unique sets is called normalization. This is implemented to
imorove the performance of the RDBMS, such as reduceces redunbdancy of data and data inconsistency.
Normalization is the process of removing redundant data from your tables in order to improve storage
efficiency, data integrity and scalability
Database normalization is a series of steps followed to obtain a database design that allows for consistent
storage and efficient access of data in a relational database .These steps reduce data redundancy and the
risk of data becoming inconsistent
shiva
8