segunda-feira, 7 de maio de 2012

Perguntas e respostas sobre DB2

Desenvolvido por Carlos Alberto Dornelles - Analista de Sistemas - Brasília DF.

001) Como você descobre o número total de linhas em uma tabela DB2?
Use SELECT COUNT(*) ... na query do db2


002) Como voce elimina valores duplicados em um SELECT no DB2?
Use SELECT DISTINCT ... na query do db2


003) Como voce seleciona uma linha usando os índices no DB2?
Especifica as colunas que são íncides na clausúla WHERE na query do db2


004) Como voce acha o valor máximo de uma coluna no db2?
Use SELECT MAX(...) .. na query do do db2


005) Como voce seleciona os primeiros 5(cinco) characteres da coluna FIRSTNAME no DB2 da tabela EMP ?
SELECT SUBSTR(FIRSTNAME,1,5) FROM EMP;


006) O são funções agregadas?
São funções matemáticas para serem usadas na clausúla SELECT


007) Pode voce usar a função MAX em uma coluna CHAR?
Sim


008) Meu comando SQL SELECT AVG(SALARY) FROM EMP está trazendo um resultado errado. Porque?
Porque a coluna SALARY foi declarada como NULLs e algumas linhas cuja acoluna que possuem valores NULLs também são contadas.


009) Como você concatena o FIRSTNAME e LASTNAME da tabela EMP a fim de obter um nome completo?
SELECT FIRSTNAME || ‘ ‘ || LASTNAME FROM EMP


010) Como é usado a função VALUE?
1. Avoid -ve SQLCODEs by handling nulls and zeroes in computations
2. Substitui por um valor válido qualquer NULLS usado na query.


011) O que é UNION,UNION ALL?
UNION : elimina duplicatas
UNION ALL: retém duplicatas
Ambos são usados para combinar os resultados de comandos SELECT diferentes.
Suponha que eu tenho cinco comandos SELECT conectados por UNION/UNION ALL, quantas vezes eu deveria especificar UNION para eliminar as linhas duplicadas?
Uma vez.


012) Quais as restrições do uso do UNION embutido no SQL?
Tem que estar em um CURSOR.


013) Na cláusula WHERE o que é BETWEEN e IN?
BETWEEN traz uma gama de valores enquanto o IN traz uma lista de valores.


014) O BETWEEN comtempla os valores extremos especificados?
Sim.


015) O que é ' LIKE' usado dentro da cláusula WHERE? O que são os carateres de wildcard?
LIKE é usado para partidas de STRING parciais. ‘%’ ( para uma string de muitos caracteres ) e ‘_’ (para qualquer caráter único ) são os dois caracteres wildcard.


016) Quando voce deve usar o comando LIKE?
Para dar partida a uma pesquisa e.g. para pesquisar o empregado por nome, voce naõ necessita especificar o nome completo; usando LIKE, voce pode pesquisar for parte do nome, por exemplo.


017) O que é o significado de sublinha (‘_ ') na declaração LIKE ?
Para pesquisa de qualquer caracter único.


018) O que voce realiza com GROUP BY ... e a cláusula HAVING?
GROUP BY as linhas selecionadas com valores distintos da coluna pela qual sera agrupada.
HAVING seleciona grupos que tenham os critérios especificados


019) Considere que a coluna PROJECT da tabela de empregados é NULL. Como voce seleciona uma coluna com NULL?
SELECT EMPNO
FROM EMP
WHERE PROJECT IS NULL


020) Qual é o resultado desta query se nenhuma linha for selecionada:
SELECT SUM(SALARY)
FROM EMP
WHERE QUAL=‘MSC’
NULL


021) Por que o SELECT * não é preferido em programas com SQL embutido?
Por três razões:
Se a estrutura da tabela for modificada (um campo é somado), o programa terá que ser modificado.
Porque o programa irá recuperar colunas que podem não serem usadas no programa, sobrecarregando a area de I/O.
A chance de um index único será perdido.
O que é subqueries correlatas?
A subquery in which the inner (nested) query efers back to the table in the outer query. Correlated subqueries must be evaluated for each qualified row of the outer query that is referred to.


022) What are the issues related with correlated subqueries?
????


023) O que é um CURSOR? Porque deverá ser usado?
Cursor é um dispositivo de programação que permite o SELECT achar varias linhas de uma tabela mas lhe devolve de cada vez uma de
cada vez.
Cursor deverá ser usado porque a host language pode tratar só uma linha de cada vez.


024) Como você recuperaria linhas de uma tabela do DB2 em SQL embutido?
Usando o comando SELECT, ou usando o CURSOR.
Sem o uso do cursor, que outros modos estão disponíveis a você recuperar uma linha de uma tabela em SQL embutido?
Usando o comando SELECT.


025) Onde voce especificaria o comando DECLARE CURSOR?
Veja outras perguntas a respeito dessa questão.



052) Where do you specify them ?
ISOLATION LEVEL is a parameter for the bind process.

053) When do you specify the isolation level? How?
During the BIND process. ISOLATION ( CS/RR )...
I use CS and update a page. Will the lock be released after I am done with that page?
No.

054) What are the various locking levels available?
PAGE, TABLE, TABLESPACE

055) How does DB2 determine what lock-size to use?
1. Based on the lock-size given while creating the tablespace
2. Programmer can direct the DB2 what lock-size to use
3. If lock-size ANY is specified, DB2 usually chooses a lock-size of PAGE

056) What are the disadvantages of PAGE level lock? - RAMESH www.geocities.com/srcsinc
High resource utilization if large updates are to be done

057) What is lock escalation?
Promoting a PAGE lock-size to table or tablespace lock-size when a transaction has acquired more locks than specified in NUMLKTS. Locks should be taken on objects in single tablespace for escalation to occur.

058) What are the various locks available?
SHARE, EXCLUSIVE, UPDATE

059) Can I use LOCK TABLE on a view?
No. To lock a view, take lock on the underlying tables.

060) O que é ALTER ?
Comando do SQL usado para alterar as definições dos objetos do DB2.

061) O que é um DBRM, PLAN ?
DBRM: DataBase Request Module, has the SQL statements extracted from the host language program by the pre-compiler.
PLAN: A result of the BIND process. It has the executable code for the SQL statements in the DBRM.

062) What is ACQUIRE/RELEASE in BIND?
Determine the point at which DB2 acquires or releases locks against table and tablespaces, including intent locks.

063) What else is there in the PLAN apart from the access path?
PLAN has the executable code for the SQL statements in the host program

064) What happens to the PLAN if index used by it is dropped?
Plan is marked as invalid. The next time the plan is accessed, it is rebound.

065) What are PACKAGES ?
They contain executable code for SQL statements for one DBRM.

066) What are the advantages of using a PACKAGE?
1. Avoid having to bind a large number of DBRM members into a plan
2. Avoid cost of a large bind
3. Avoid the entire transaction being unavailable during bind and automatic rebind of a plan
4. Minimize fallback complexities if changes result in an error.

067) What is a collection?
a user defined name that is the anchor for packages. It has not physical existence. Main usage is to group packages.
In SPUFI suppose you want to select max. of 1000 rows , but the select returns only 200 rows.

068) What are the 2 sqlcodes that are returned?
100 ( for successful completion of the query ), 0 (for successful COMMIT if AUTOCOMMIT is set to Yes).

069) How would you print the output of an SQL statement from SPUFI?
Print the output dataset.

070) How do you pull up a query which was previously saved in QMF?
??

071) Lot of updates have been done on a table due to which indexes have gone haywire. What do you do?
Looks like index page split has occurred. DO a REORG of the indexes.

072) O que é uma SQL dinâmico?
Um SQL dinâmico é um comando SQL criado no programa em tempo de execução

073) Quando é determinado o acesso para um SQL dinâmico?
Em tempo de execução, quando o comando PREPARE é emitido.

074) Suppose I have a program which uses a dynamic SQL and it has been performing well till now. Off late, I find that the performance has deteriorated. What happened?
Probably RUN STATS is not done and the program is using a wrong index due to incorrect stats.
Probably RUNSTATS is done and optimizer has chosen a wrong access path based on the latest statistics.

075) How does DB2 store NULL physically?
as an extra-byte prefix to the column value. physically, the nul prefix is Hex ’00’ if the value is present and Hex ‘FF’ if it is not.

076) How do you retrieve the data from a nullable column?
Use null indicators. Syntax ... INTO :HOSTVAR:NULLIND

077) What is the picture clause of the null indicator variable?
S9(4) COMP.

078) What does it mean if the null indicator has -1, 0, -2?
-1 : the field is null
0 : the field is not null
-2 : the field value is truncated

079) How do you insert a record with a nullable column?
To insert a NULL, move -1 to the null indicator
To insert a valid value, move 0 to the null indicator

080) What is RUNSTATS?
A DB2 utility used to collect statistics about the data values in tables which can be used by the optimizer to decide the access path.
It also collects statistics used for space management. These statistics are stored in DB2 catalog tables.

081) When will you chose to run RUNSTATS?
After a load, or after mass updates, inserts, deletes, or after REORG.

082) Give some example of statistics collected during RUNSTATS?
# of rows in the table
Percent of rows in clustering sequence
# of distinct values of indexed column
# of rows moved to a nearby/farway page due to row length increase

083) What is REORG? When is it used?
REORG reorganizes data on physical storage to reclutser rows, positioning overflowed rows in their proper sequence, to reclaim space,
to restore free space. It is used after heavy updates, inserts and delete activity and after segments of a segmented tablespace have
become fragmented.

084) What is IMAGECOPY ?
It is full backup of a DB2 table which can be used in recovery.

085) When do you use the IMAGECOPY?
To take routine backup of tables
After a LOAD with LOG NO
After REORG with LOG NO

086) What is COPY PENDING status?
A state in which, an image copy on a table needs to be taken, In this status, the table is available only for queries. You cannot update
this table. To remove the COPY PENDING status, you take an image copy or use REPAIR utility.

087) What is CHECK PENDING ?
When a table is LOADed with ENFORCE NO option, then the table is left in CHECK PENDING status.
It means that the LOAD utility did not perform constraint checking.

088) What is QUIESCE?
A QUIESCE flushes all DB2 buffers on to the disk. This gives a correct snapshot of the database and should be used before and after
any IMAGECOPY to maintain consistency.

089) What is a clustering index ?
Causes the data rows to be stored in the order specified in the index. A mandatory index defined on a partitioned table space.

090) How many clustering indexes can be defined for a table?
Only one.

091) What is the difference between primary key & unique index?
Primary : a relational database constraint. Primary key consists of one or more columns that uniquely identify a row in the table.
For a normalized relation, there is one designated primary key.
Unique index: a physical object that stores only unique values. There can be one or more unique indexes on a table.

092) What is sqlcode -922 ?
Authorization failure

093) What is sqlcode -811?
SELECT statement has resulted in retrieval of more than one row.

094) What does the sqlcode of -818 pertain to?
This is generated when the consistency tokens in the DBRM and the load module are different.

095) Are views updateable ?
Not all of them. Some views are updateable e.g. single table view with all the fields or mandatory fields.
Examples of non-updateable views are views which are joins, views that contain aggregate functions(such as MIN), and views that
have GROUP BY clause.

096) If I have a view which is a join of two or more tables, can this view be updateable?
Não.

097) What are the 4 environments which can access DB2
TSO, CICS, IMS and BATCH

098) What is an inner join, and an outer join ?

Inner Join: combine information from two or more tables by comparing all values that meet the search criteria in the designated column
or columns of on e table with all the clause in corresponding columns of the other table or tables. This kind of join which involve a match in both columns are called inner joins.

Outer join is one in which you want both matching and non matching rows to be returned. DB2 has no specific operator for outer joins, it can be simulated by combining a join and a correlated sub query with a UNION.

099) What is FREEPAGE and PCTFREE in TABLESPACE creation?
PCTFREE: percentage of each page to be left free
FREEPAGE: Number of pages to be loaded with data between each free page

100) What are simple, segmented and partitioned table spaces ?
Simple Tablespace:
Can contain one or more tables
Rows from multiple tables can be interleaved on a page under the DBAs control and maintenance
Segmented Tablespace:
Can contain one or more tables
Tablespace is divided into segments of 4 to 64 pages in increments of 4 pages. Each segment is dedicated to single table.
A table can occupy multiple segments
Partitioned Tablespace:
Can contain one table
Tablespace is divided into parts and each part is put in a separate VSAM dataset.

101) What is filter factor?
One divided by the number of distinct values of a column.

102) What is index cardinality?
The number of distinct values a column or columns contain.

103) What is a synonym ?
Synonym is an alternate name for a table or view used mainly to hide the leading qualifier of a table or view. A synonym is accessible
only by the creator.

104) What is the difference between SYNONYM and ALIAS?

SYNONYM: is dropped when the table or tablespace is dropped. Synonym is available only to the creator.

ALIAS: is retained even if table or tablespace is dropped. ALIAS can be created even if the table does not exist.
It is used mainly in distributed environment to hide the location info from programs.
Alias is a global object & is available to all.

105) What do you mean by NOT NULL WITH DEFAULT? When will you use it?
This column cannot have nulls and while insertion, if no value is supplied then it wil have zeroes, spaces or date/time depending on
whether it is numeric, character or date/time.
Use it when you do not want to have nulls but at the same time cannot give values all the time you insert this row.

106) What do you mean by NOT NULL? When will you use it?
The column cannot have nulls. Use it for key fields.

107) When would you prefer to use VARCHAR?
When a column which contains long text, e.g. remarks, notes, may have in most cases less than 50% of the maximum length.

108) What are the disadvantages of using VARCHAR?
1. Can lead to high space utilization if most of the values are close to maximum.
2. Positioning of VARCHAR column has to be done carefully as it has performance implications.
3. Relocation of rows to different pages can lead to more I/Os on retrieval.

109) How do I create a table MANAGER ( EMP#, MANAGER) where MANAGER is a foreign key which references to EMP# in the same table?
Give the exact DDL.
First CREATE MANAGER table with EMP# as the primary key. Then ALTER it to define the foreign key.
When is the authorization check on DB2 objects done - at BIND time or run time? At run time.

110) What is auditing?
Recording SQL statements that access a table. Specified at table creation time or through alter.

Nenhum comentário:

Postar um comentário