Classification: GE Internal
Classification: GE Internal
Classification: GE Internal
Classification: GE Internal
2. When we have to update our table frequently. We can see if an optimizer chose to use an index by using
showplan on option. Generally it is up to the optimizer to use indexes or not. It is common opinion that
on a small table (<500 rows) the optimiser would prefer a table scan. On a big table (>10 000 rows) usage
of indexes is more probable.
17. When does the optimiser ignore the indexes?
When we use like in SQL statement.
18. Do indexes in Sybase affect the physical order of data in the table?
If there is a clustered index on the table, the actual data is sorted in the index order (by the indexed
column). Non-clustered indexes do not reorder the actual data (the data is in the order in which it is
inserted).
19. If you have a column that gets updated frequently, what kind of index will you create on this
column to improve the performance, Clustered or Non-clustered?
Non-clustered. If you create a clustered index on this column, the data will be physically re-arranged in
the DataBase after each Update and this will slow down the performance.
20. What do you know about fill factor?
Fill factor of an index specifies how many levels of non-leaf pages the index has.
21. What is the difference between indexes and keys?
Keys are not the same as indexes. Keys are defined at logical design time while indexes are defined at
physical design time for performance and other reasons.
22. What is a Transaction?
Transaction is a logical unit of work. We may say it is a set of SQL statements.
23. What is a View? What is the main purpose for a View?
A View is a stored select statement that behaves like a table. The primary purpose of a view is:
*4
Security
*5
Simplify long Query
*6
Ad Hoc Query.
A View is a pseudo-table which contains a select statement from one or more databases.
a. Allows us to combine two databases or two or more tables.
b. For security reasons (it does not let the user obtain real database table.)
c. It is stored as a query in the database.
A View is a virtual table (it is not a real table, it is just an entry in the system catalog). It is a DB object
which we use for security purposes or to narrow the scope of data (View does not occupy any space. Only
the view created as a result of simple select of all columns from one table can be updated. Cannot use:
ORDER BY, COMPUTE, INTO, DISTINCT when creating a rule)
24. What is a Trigger? How do you create a Trigger?
Triggers are a special kind of stored procedures that go into effect when you insert, delete, update data in
a specified table or column.
Or
Triggers are SQL statements which automatically execute when a row is inserted, deleted, updated in a
table. We create a trigger by specifying the table and the data modification commands that should fire or
activate the trigger. We can create a trigger using the Create clause which creates and names the trigger,
the ON clause gives us the name of the table that activates the trigger (called trigger table). The FOR
clause tells us that the action for which trigger was created. Example:
Create trigger t1
Classification: GE Internal
on titles
for insert, update, delete
as
SQL_statement
for (insert, update)
as
if update(column_name)
[(and/or} update(column_name)]. . .
SQL statement
Triggers cannot be called directly. Triggers do not take parameters
25. Which Sybase system tables are used when you write triggers?
The Inserted and Deleted tables are used when writing triggers. Inserted Table holds any rows added to a
table when you execute Insert or Update SQL statement. Deleted Table holds any rows removed from the
table when you execute Delete or Update SQL statements.
26. How many triggers can you specify for one DataBase Table?
A table can have a maximum of three triggers : Update trigger,
Insert trigger,
Delete trigger.
However, we can create a single trigger that will apply to all three user actions (Update, Delete, Insert).
27. Which statements are not allowed in a trigger?
In SQL Servers triggers are not allowed:
1. Alter Table, Alter Database;
2. Truncate table;
3. Grant and Revoke statements;
4. Update statistics; select into.
5. Creation of objects
6. Neither views nor temporary tables can have triggers.
28. Why do we need Triggers?
To ensure referential integrity. Declarative integrity cannot be used to perform cascaded updates or
deletes when the primary key is updated or deleted. The programmer can implement alternative solutions
using triggers.
29. How can you obtain the source code of a trigger in SQL Server?
Using sp_helptext
<trigger name>
30. Can you call Stored Procedures from Triggers?
Yes.
31. Can you create temporary tables in Triggers?
No, we cannot.
32. What is the difference between HAVING and WHERE keywords in SQL?
WHERE filters out the rows. Where clause limits the rows displayed (eliminates rows, cannot include
aggregate functions)
HAVING filters out the groups. HAVING clause limits the groups displayed (eliminates groups, can
include aggregate functions, be used with GROUP BY clause). GROUP clause is the command to search
through the specified rows and treat all the rows in which the contents of the specified column is identical
as one row. As the result, only contents of the specified rows and aggregate functions can be included in
Classification: GE Internal
the select list for a SQL command using the GROUP BY clause. WHERE clause specifies the connection
between tables named in a FROM clause and restricts the rows to be included in the result. HAVING sets
conditions for the GROUP BY clause and restricts the groups in the result.
34. What is Data Dictionary? How is it used?
Data Dictionary is stored in each database. The info regarding the database(s) structure and components is
contained in the data dictionary for the database. The data dictionary, also called the system catalog, is
stored as data in the system tables in each database.
35. What is the name of the DataBase in which system-related information is stored?
Master Database which has system catalog, system procedure . .
36. What are the system databases in SQL server?
Beside users databases SQL SERVER always has 3 databases: MASTER, MODEL, and TempDB.
Stored procedure DB
MASTER is used internally by SQL Server to store information about users databases;
MODEL is used as a template to create a new users database.
TempDB is used to store temporary info like temporary tables if you use them in SPs.
37.
Classification: GE Internal
Classification: GE Internal
*10
*11
52. What is an outer join? What kind of outer joins do you know?
An outer join is defined as a join in which both matching and unmatching rows are returned. We use *=
to show all the rows from the first defined table. (Left outer-join)
We know left outer join and right outer join.
53. How do we join two or more tables?
We use Select statement with Where clause, where we specify the condition of join.
54. Give an example of outer join?
An outer join forces a row from one of the participating tables to appear the result set if there is no
mattering row. An asterisk(*) is added to the join column of the table which might not have rows to
satisfy the join condition. For example:
SELECT cust.cust_id, cust.cust_lname, sal.sal_id
FROM customer cust, salesman sal
WHERE cust.sal_id *= sal.sal_id
Used for reports. There is no matching between two columns.
55. How do you understand left join?
56. How do you get a count of returned rows?
Using a global variable @@rowcount.
57. How do you get a Count of non null values in a column?
Count (column_name) returns number of non null values in the column.
57. What are the aggregate functions? Name some.
Aggregate functions are functions that work on groups of information and return summary value.
Count(*) number of selected rows;
count(name_column) number of non-null values in a column;
max( ) highest value in a column;
sum( ) total of values in a column;
min( ) lowest value in a column
avg( ) average of values in a column.
Aggregates ignore Null value (except count(*)).
Sum() and avg() work with numeric values.
Only one row is returned (if a GROUP BY is not used).
Aggregates may not be used in WHERE clause unless it is contained in subquery:
(select title_id, price
from titles
where price >(select avg(price) from titles).
58. What can be used with aggregate functions?
1. More than one aggregate function can be used in a SELECT clause.
SELECT min(advance), max(advance)
2. DISTINCT eliminates duplicate value before applying aggregate. Optional with sum(), avg() and
count. Not allowed with min(), max() and count(*)
SELECT avg(distinct price)
Classification: GE Internal
Classification: GE Internal
Classification: GE Internal
Classification: GE Internal
operator combines the results of two or more queries into a single result set consisting of all the rows
belonging to A or B or both. Union sorts and eliminates duplicated rows.
82. From Employee table how to choose employees with the same Last Name, First Name can be
different?
Use SelfJoin. (look at the table as at two different)
SELECT a.first_name, b.last_name
FROM a.student,b.student
WHERE a.student.student_id = b.student.student_id
83. How can you handle Nulls values in DataBase?
We have to make sure that columns that are part of the primary key( or just an important column) are not
nulls in table definition.
If IsNull (column)
if not IsNull(column)
SQL Server Fundamentals.
Consider the following code (it is the basis for Questions 1 - 8 ) :
CREATE table my_table( a int not NULL, b int default 10 NULL)
GO
CREATE rule b_rule as b_val between 0 and 100
GO
sp_bindrule b_rule, my_table.b
GO
CREATE view sample_view as SELECT * from my_table
GO
alter table my_table ADD c varchar(20) NULL
GO
alter table my_table ADD constraint b_check
check(b between -10 and 10)
GO.
4. What value will be inserted into the table for column b by the following insert statement :
INSERT sample_tab(a, b) values (1, NULL)
Explicitly providing NULL is essentially a value (no value) and the default will not be used.
5. If there were 50 rows already in the table when the default was bound to column b and 20 of the
rows had no values for column b, what value will those rows have for column b after the default is
bound?
Defaults, rules apply only to future rows added to the table. Existing rows are unaffected.
6. If a file containing 20 rows is bulk copied into a table and 5 of the rows do not have values for
column b, what value will those rows have for column b after the bcp is completed?
10 Defaults are recognized during bcp.
7. Will file containing rows that have negative values for column b be added during bulk copying?
Classification: GE Internal
Yes. Rules, triggers and constrains are not recognized during bulk copy operations.
8. What columns will the user see if he runs the following SELECT statement :
SELECT * from sample_view.
Columns a and b. Although the view executes a select *, * is expanded during view compilation.
Column c does not exist at this point.
9. What values are allowed in column b for inserts/updates?
0 to 10. The rule is checked first (between 0 and 100), then the constraint will be checked (-10 to 10). The
valid range is the intersection.
10. What methods can be used to enforce a business rule requiring a value in column b to be greater
than a value in column a for an insert/update?
A table-level constraint or an insert/update trigger.
11. What command would you use to change the default value in column b to 5?
Alter my_table replace b default 5.
12. What system table contains information about objects, such as tables, defaults, and triggers
within a Database?
Sysobjects.
13. How many pages are allocated when a table is created?
An extent of 8 pages.
14. How is clustered index different from a non-clustered index?
Clustered indexes dictate the physical order of data. The leaf level of the clustered index is the data. A
non-clustered index has a row in the leaf level of the index for every row in the table.
15. Can a clustered index be placed on a separate device from a table?
No.
16. Can a column be deleted from a table?
No. (Not officially, although a student once asked me this question. I answered, with authority Never.
I just did it! he said. There is an undocumented System 10 feature : alter table t1 drop c1 from table t1.
The implementation is interesting : the column is undefined, but all the data remains untouched until the
rows are modified. As each row is modified, the column is nullified.
17. What command allows you to add columns to a table?
Alter table
18. How many columns with the identity property can be created in a table?
One or Zero.
19. What system datatype must be used for identity columns?
Numeric, with a definition of (n, 0) where n is the number of digits.
20. What global variable can you query to determine the last identity value inserted into a table?
@@identity
21. Explain the difference between char and varchar datatypes?
Classification: GE Internal
Char is fixed-length datatype whose trailing spaces are stored. Varchar is a variable-length datatype.
Nullable char is stored like varchar because it is variable length either no length or the declared length.
22. How is the string Bob in a char (10) not-null column stored differently than the same string in
a varchar(10) not-null column?
This string would store 10 bytes in the char field (the string is padded with spaces) and 3 bytes in the
varchar field (plus 1 byte overhead).
23. Define what is meant by NULL?
The absence of a value.
24. How are null values handled by aggregate functions?
NULLs are not considered in aggregates.
25. What Sybase function can substitute a value for NULL in a query?
IsNull (expression, value)
26. What is the restriction on updating base tables through a view, if the view is defined on multiple
tables?
The columns being updated must exist in only one of the tables.
27. What is the restriction on inserting data into a base table through a view if the view contains
only a subset of the columns in the base table?
The columns that are not part of the view must be Nullable or have a default.
28. What is the restriction on deleting rows through a multitable view?
Deletes are not allowed in multitable views.
29. What is the maximum triggers that can be created on a table?
Three triggers : insert, update, and delete triggers. (Note that there is a column called seltrig in Sysobjects,
but it is not currently used.)
30. If update on table_A fires a trigger that updates table_B, and table_A has an update trigger
defined on it, will the trigger on table_B be executed?
Yes, in the default server configuration. If the nested triggers configuration value is set to 0, the trigger on
table_B would not fire.
31. If an update of a row in table_A fires a trigger that updates another row in table_A, will the
trigger on table_A execute again?
No, by default. If nesting is allowed and set self_recursion on has been executed, the trigger would fire.
32. What are the names of the tables that are accessible only from within a trigger when a trigger is
executed?
Inserted and deleted.
33. What is the structure of the tables referred to in the previous question?
The exact structure of the table on which the trigger is created.
Classification: GE Internal
34. Where are tables mentioned in the previous two questions located?
In memory. (Alternative answer : They actually are special views of syslogs)
35. When is the Update(column_name) function used, and when it is true?
Update(column_name) is used in a trigger to determine whether the value of a column has been modified.
In an insert trigger, the function is true if a non-null value was inserted; in an update trigger, the function
is true if a column was named in the update statement set clause.
36. An insert trigger is created on a table that validates whether one of its column values exists in
another table before allowing the insert to succeed. A file that contains invalid values for that
column is bulk copied into the table. Will the rows be inserted by the bulk copy?
Yes, bcp bypasses triggers, rules and constraints (but not defaults)
37.
An update trigger exists on the titles table which contains 1,000,000 rows.
If you issue the following statement, how often does the trigger fire?
UPDATE titles
set price = price + $2
where type = mod_cook
One time. A trigger fires once per modification statement whether the statement modifies zero, one or
many rows in a table.
38. If a table is created with a unique constraint on a column, will that column
allow NULL values?
Yes, but only once.
39. What if the column is created with a primary key constraint?
No. The primary key constraint requires the column to be declared as not NULL.
40. If a view is created on table my_table and that table is renamed to new_table will the view
still work?
Yes. During compilation, the server converts an object name to an object ID. The rename changes only
the name.
41. If a column is added to a table after a view has been defined on the table, what must be done to
make the column accessible through the view?
Drop and re-create the view.
42.
Classification: GE Internal
55. What is the difference between the following two select statements?
SELECT title, type, price from titles
ORDER BY type
COMPUTE avg(price) by type;
Classification: GE Internal
Classification: GE Internal
Classification: GE Internal
Classification: GE Internal
91. What if those columns in the previous question already had a rule that was bound explicitly to
the column?
An explicit bind to a column overrides a bind to a datatype. The bind to the datatype would have no
effect.
92. If a column has a rule bound to it and you attempt to bind another rule to that column, what
happens?
The new rule will replace the old one (the existing rule does not have to be unbound).
93. How are database objects fully qualified?
dbname.username.objectname
Classification: GE Internal
Classification: GE Internal
Stored procedures are blocks of SQL code which have been compiled and stored on the server. It may be called
from client processes or within triggers.
Or
A Stored Procedure is a set of precompiled and preoptimized SQL statements that performs some database
operation. Stored Procedures reside where the DataBase resides and you can access them as needed.
2. Why do we need Stored Procedures?
Stored Procedures make our process faster. One time we compile select and then just use it. They give us
completely controls how information is stored and retrieved. Security reason. Defined business rule and
Maintenance
or
the benefits of using stored Procedures :
*12
executes much faster, because the path is not created each time of execution of Stored Procedure
*13
can be shared between multiple users;
*14
it is much easier to manage them when they stored in DB, then embedded SQL.
or
Use stored procedures to improve:
security
consistency
data integrity
response time
2a. What benefits of Stored Procedures ?
*15 run faster than the same commands executed interactively as a batch
*16 reduce network traffic
*17 enforce consistency throughout the database
*18 help provide security
*19 reduce operator error
3. How do you declare a Cursor for the Stored Procedure?
Use Declare cursor statement:
DECLARE emp_pro procedure for GetName
@emp_name = :EditEmpName,:@emp_salary = 5000;
4. How to use Stored Procedure from another one?
Execute by name.
5. What is allowed in Stored Procedure:
*20
create view
*21
create default
*22
create trigger
*23
create procedure
*24
create table ? Nothing
Classification: GE Internal
2.Our server must have the remote server in its list of known servers (sp_addserver)
3.The remote server name must be in the interfaces file
4.We Must have added appropriate remote login on the system being accessed
We can execute any procedure on the remote SQL Server using the server name as part of the
identifier.
Exec.servername.dbo.procedurename
We can pass value as parameters to a remote procedure from the SQL batch or procedure that contains the
EXECUTE statement for the remote procedure. The Result will appear on our local terminal.
7. What are : @@rowcount, @@error?
@@rowcount is a Global variable which stores the number of rows affected by the most recent data modification
operation. It is used to check how many rows were affected by a previous @@error a section of code may be
executed based on the value returned by error code.
8. What happens if you rename the object referenced by a Stored Procedure?
We must drop and recreate a procedure if we rename any of the objects it references. A stored procedure that
references a table or view whose name has been changed may seem to work fine until SQLServer recompiles it.
Recompilation takes place for many reasons and without notification to the user.
9. What is sp_depends?
sp_depends is system a procedure that allows us to get a report (list) of the objects referenced by a procedure. We
usually use it before when we need to drop or rename object.
10. How do we create a Stored Procedure? Delete it?
Create procedure name
@- specify parameters (variable)(if we need any)
as
select . . . .
If we use more than one SQL statement we have to use begin and end keyword
delete storedprocedure - Drop procedure_name
11. Name some of the Sybase system Stored Procedures you made use of. What did you use them
for?
The master DB contains useful stored procedures called system procedures that access the system tables. System
procedures begin with sp_ and can be run from any DB. The master DB contains a library of useful stored
procedures which access the system tables.
Sp_help - prints all database objects and data types
sp_rename renames an object
sp_helpindex indexes information on the table
sp_depends displays dependency information
sp_who displays currently logged on users
sp_helptext prints text of store procedure, trigger, view, default of rule
sp_lock displays information about locks
sp_adduser
sp_dropgroup
sp_addgroup
sp_droplogin
sp_addlogin
sp_dropuser
sp_changegroup
sp_lockloginsp
sp_help
sp_password
sp_helpdb
sp_user_id
sp_helpgroup
sp_user_name
sp_helpuser
Classification: GE Internal
Classification: GE Internal
20. What system Stored procedures do you use working with SP?
SP_helptext - to view the text of store procedure
SP_rename - to rename a store procedure
21. How can be specify parameters for SP?
The parameters can be specified by position or by name.
22. What is a reason to use the default values for parameters in SP?
If we defined default value for parameters in SP we can check if user provided values for parameters when the
executed SP.
25. What statement do you use if you want to execute SP from the script?
DECLARE - to declare SP
EXECUTE - TO EXECUTE SP
FETCH
- TO FETCH the result set into the variable (usually in the LOOP)
CLOSE
- is necessary if SP returns the RESULT SET
Classification: GE Internal