Sybase Training
Sybase Training
TRAINING
Sybase
Architecture
What is Sybase Server?
• Scalabale High Performance Database
– Client/Server Architecture
– Multithreaded Server
– User Connections implemented as threads
– RAM requirement per user = 50KB
– Scalability
– Multithreaded Operation not possible
– Parallel processing not possible
System Databases
• master database
• model database
• sybsystemprocs
• tempdb
• sybsecurity
• sybsyntax
Master Database
Indexes sysindexes
Datatype systypes
sysconstraints
Constraints sysreferences
System Procedures
• An easy way to query system tables
• System Procedure is a precompiled
collection of SQL statements
• Are located in sybsystemprocs but
can be executed from any database
System Procedures
sp_help [objname]
sp_helpdb [dbname]
sp_helpindex tabname
sp_spaceused [objname]
Allocating Space
Allocating Storage
• Device
• Database
• Allocation Unit
• Extent
• Page
Devices
• Devices are hard disk files that store
databases, transaction logs, and
backups
• One device can hold many databases
and one database can span multiple
devices
• Only SA can create devices
Creating a Device
DISK INIT
name=‘logical_name’,
physname = ‘physical name’,
vdevno=virtual_dev_no,
size = num_of_2K_blocks
[, VSTART= virtual_address]
DISK INIT
DISK INIT
NAME = ‘hcl_dev1’,
PHYSNAME=‘C:\HCL\DATA\hcl_dat’,
VDEVNO=3,
SIZE = 8192
DISK INIT
NAME = ‘hcl_dev2’,
PHYSNAME=‘C:\HCL\DATA\hcl_log’,
VDEVNO=4,
SIZE = 1024
DISK INIT
• Maps the specified physical disk
operating system file to a database
device name
• Lists the new device in
master..sysdevices
• Prepares the device for database
storage
vdevno
• Used to map sysdevices, sysusages
and sydatabases
• Must be less than device parameter
in master
• Total no. of devices available is 255
Memory Allocation for
devices
• Memory allocated at Server startup
• 50KB/device
• Over configuring can be a waste of
memory
• 20 devices will take up 1 MB RAM
Devices
Configured Value –
Sp_configure “Number of devices”
eg sp_helpdevice master
• Dropping a device
sp_dropdevice logical_name
Managing Devices
sp_diskdefault master, defaultoff
Sp_dropdevice tapedump1
Default devices
• Devices not to be used as default
devices
– Master
– Device used for sybsecurity
– Devices used for transaction logs
Dropping of devices
• Enforce uniqueness
• Speed up joins
• Speeds data retreival
• Speeds ORDER BY and GROUP BY
Indexing
• Columns to consider for indexing
– Primary Key
– Columns frequently used in joins
– Columns frequently searched in ranges
– Columns retrieved in sorted order
Indexing (contd)
• Columns that should not be indexed
– Columns seldom referenced in query
– Columns that contain few unique
values
– Columns defined with text, image, or
bit datatypes
– When Update performance has a
higher priority than SELECT
performance
Creating An Index
Validate Names
Check Protection
Check Protection
Substitute Parameters
Optimize
Compile
Execute
Stored Procedures
Main performance gain is the capability
of Sybase server to save the
optimised query plan generated by
the first execution of the stored
procedure in procedure cache and to
reuse it for further execution
Execution of SP
FIRST Execution –
• Locate SP on disk and load into
cache
• Substitute parameter values
• Develop optimisation plan
• Compile optimisation plan
• Execute from cache
Execution of SP
Subsequent Executions
• Locate SP in cache
• Substitute parameter values
• Execute from cache
Stored Procedures
• Advantaqge of cost based optimizer
is that it has the capability of
generating the optimal query plan for
all plans based on search criteria
• For certain type of queries (eg range
queries) optimiser may at times
generate different plans
Stored Procedures
• In situations where parameter values
can be different for every execution,
use CREATE PROCEDURE WITH
RECOMPILE option
• In case a particular execution has to
use a different plan use EXECUTE
with RECOMPILE
Stored Procedures
• If an index used by a stored
procedure is dropped, Sybase
detects it and recompiles the
procedure
• Adding additional indexes or running
UPDATE STATISTICS does not cause
automatic recompilation
Stored Procedures
• Statistics Updation has to be followed
by sp_recompile <table name>to
generate a new query plan
• Addition of an index has also to be
followed by sp_recompile
Stored Procedures
Create proc get_order_data (@flag tinyint,
@value smallint)
as
If @flag=1
Select * from orders where price=@value
Else
Select * from orders where qty=@value
should be converted to …..
Stored Procedures
Create proc get_orders_by_price (@price
smallint)
as
select * from orders
where price =@value
274
Why Triggers
• Cascading Actions are not available
with DRI i.e. when Primary Key is
Updated or Deleted, Corresponding
Foreign Keys do not get
automatically changed
• Maintaining duplicate data
• Keeping derived columns current
275
Special Tables for Triggers
• Inserted and Deleted
• Are available only to triggers
• Have the same structure as the
trigger table
• Can be joined to other tables in the
database
281
INSERT Trigger
Trigger Table
Inserted
282
INSERT Trigger
eg. CREATE TRIGGER loan_ins
ON loan for insert
AS
UPDATE copy
SET ON_LOAN=‘y’
FROM COPY,inserted
WHERE copy.isbn=inserted.isbn
AND copy.cop_no=inserted.copy_no
284
DELETE Trigger
Trigger Table
Deleted
285
UPDATE Trigger
Updated Table
Table
Inserted
Deleted
287
UPDATE Trigger
CREATE TRIGGER mem_upd
ON member
FOR UPDATE
AS
IF UPDATE(MEMBER_NO)
BEGIN
RAISERROR (‘Trnxn cannot be processed. \
**** Member cannot be updated.’,10,1)
ROLLBACK TRANSACTION
END
288
Transaction control in
Triggers
• Rollback transaction in a trigger rolls
back the entire transaction
• Rollback to a savepoint name rolls
back to the savepoint
• Rollback trigger rolls back the data
modification that fired the trigger
and any statements in the trigger
that are part of the transaction
292
Trigger Considerations
• Overhead is very low
• Inserted and Deleted tables are in
memory
• Location of other tables referenced by the
trigger determines the amount of time
required
• INSERT,DELETE or UPDATE in the trigger
is a part of the transaction
• Nested triggers are set to true by default
• Self recursion of triggers does not happen
unless set
293
Cursors
Benefits of Cursors
Allow a program to take action on
each row of a query result set rather
than on the entire set of rows
• Provide the ability to delete or
update a row in a table based on
cursor position
205
Cursors
A cursor consists of the following parts
Cursor result set : set of rows
resulting from execution of the
associated select statement
Cursor position : a pointer to one row
within the cursor result set
206
Cursor scope
• Session – Starts when a client logs
into SQL Server and ends on log out
• SP – Starts when SP begins
execution and ends when SP
completes execution
• Trigger – Starts when trigger begins
execution and ends when it
completes execution
207
Cursors
• Declare – declare the cursor for select
statement. Checks SQL syntax
• Open – Executes the query and creates
the result set . Positions the cursor before
the first row of the result set
• Fetch – fetches the row to which cursor
points
• Close – Closes the result set, but the
compiled query plan remains in memory
• Deallocate – drops the query plan from
memory
208
Resource requirements of
Cursors
• Memory allocated at the time of
declaration of cursor
• On open intent table lock is acquired
• When a row is fetched, page lock is
acquired
Read Only Cursors
• Use all the search arguments you can to give the optimizer
as much as possible to work with
Adding SARG to help
optimiser
1. select au_lname, title from titles t, titleauthor ta,
authors a where t.title_id = ta.title_id and
a.au_id = ta.au_id and t.title_id = "T81002"
The large table as the outer table. It will only have to read this large
table once.
The indexed table as the inner table. Each time it needs to access the
inner table, it will take only a few reads to find rows.
Combining max and min
aggregates
• When used separately min and max on indexed
columns use special processing if there is no
where clause
• Min aggregates retrieve the first value on the root
page of the index, performing a single read to
find the value
• Max aggregates follow the last entry on the last
page at each index level until they reach the leaf
level. For a clustered index, the number of reads
required is the height of the index tree plus one
read for the data page. For a nonclustered index,
the number of reads required is the height of the
index tree.
Update Operation
• Direct Updates
• Deferred Updates
•At the end of the operation, re-read the log, and make all
inserts on the data pages and insert any affected index rows
Guidelines to avoid deferred
updates
• Create at least one unique index on
the table to encourage more direct
updates
• If null values are not used , use not
null in table definition
• Use char datatype instead of varchar
wherever possible
T-SQL
Perofrmance Tips
Greater Than Query
• This query, with an index on int_col:
select * from table where int_col > 3
uses the index to find the first value where
int_col equals 3, and then scans forward to find
the first value greater than 3. If there are many
rows where int_col equals 3, the server has to
scan many pages to find the first row where
int_col is greater than 3.
/* Statement Group 1 */
end
else
begin
/* Statement Group 2 */
end contd ..
Not Exists Test
Can be rewritten as
select *
from tab
select *
from tab
select min(price) from titles uses index for both the queries
Joins and datatypes
• When joining between two columns
of different datatypes, one of the
columns must be converted to the
type of the other
• Column whose type is lower in the
hierarchy is converted
• Index cannot be used for converted
column
Joins and datatypes
select * from small_table, large_table
where smalltable.float_column =
large_table.int_column
select *
from small_table, huge_table
where small_table.char_col =
huge_table.varchar_col
Forcing the conversion to
the other side of the join
• Performance would be improved if the index on
huge_table could be used. Using the convert
function on the varchar column of the small table
allows the index on the large table to be used
while the small table is table scanned:
select *
from small_table, huge_table
where convert(varchar(50),small_table.char_col) =
huge_table.varchar_col
Parameters and Datatypes
• The query optimizer can use the values of parameters to
stored procedures to help determine costs.