0% found this document useful (0 votes)
20 views

Dbms Internals 2

database questions

Uploaded by

jeevenmr02
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
20 views

Dbms Internals 2

database questions

Uploaded by

jeevenmr02
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 18
4.2.3 Attribute Data Types and Domains in SQL Basic data types 1. Numeric data types includes + integer numbers of various sizes (INTEGER or INT, and SMALLINT) + floating-point (real) numbers of various precision (FLOAT or REAL, and DOUBLE PRECISION). + Formatted numbers can be declared by using DECIMAL(ij)—or DEC(i.j) or NUMERIC(.j)—where i precision. total aumber of decimal digits j- scale, number of digits after the decimal point R Character-string data types + fixed Jength—CHAR(n) or CHARACTER(n), where is the mmiber of characters + varying fength—VARCHAR(n) or CHAR VARYING(n) or CHARACTER VARYING(), where 7 is the maxinmm number of characters + When specifying a literal string value, it is placed between single quotation marks (apostrophes), and it is case sensitive + For fixed length strings, a shorter string is padded with blank characters to the sight * For example, ifthe value “Smith” is for an attribute of type CHAR(10), it is padded with five blank characters to become ‘Smith if needed + Padded blanks are generally ignored when strings are compared + Another variable-length string data type called CHARACTER LARGE OBJECT or CLOB is also available to specify columns that have large text values, such as documents + The CLOB maximum length can be specified in kilobytes (K), megabytes (M), or gigabytes © + For example, CLOB(20M) specifies a maximum length of 20 megabytes. 3. Bit-string data types are either of + fixed kength n—BIT()—or varying length—BIT VARYING(n), where 7 is the maxinmam umber of bits. + The default for 7, the length ofa character string or bit string, is 1 « Literal bit strings are placed between single quotes but preceded by a B to distinguish them from character strings: for example, B°10101° + Another variable-length bitstring data type called BINARY LARGE OBJECT or BLOB is also available to specify columns that have large binary values, such as images. * The maximum length ofa BLOB can be specified in kilobits (K), megabits (M). or gigabits © + For example, BLOB(30G) specifies a maxinmm length of 30 gigabits. 4. A Boolean data type has the traditional values of TRUE or FALSE In SQL, because of the ‘presence of NULL values, a three-valued logic is used, so a third possible value for a Boolean data type is UNKNOWN ‘The DATE data type has ten positions, and its components are YEAR, MONTH, and DAY in ‘the form YYYY-MM-DD 6. The TIME data type has at least eight positions, with the components HOUR, MINUTE, and SECOND in the form HH:MM:Ss. Only valid dates and times should be allowed by the SQL implementation. 7. TIME WITH TIME ZONE data type includes an additional six positions for specifying the displacement fiom the standard universal time zone, which is in the range +13:00 to -12:59 in units of HOURS:MINUTES. If WITH TIME ZONE is not included, the default is the local time zone for the SQL session. ww Additional data types 1. Timestamp data type (TIMESTAMP) includes the DATE and TIME fields, plus a minimum of six positions for decimal fractions of seconds and an optional WITH TIME ZONE qualifier. 2. INTERVAL data type. This specifies an imterval—a relative value that can be used to increment oc decrement an absolute value of a date, time, or timestamp. Intervals are qualified to be either YEAR/MONTH intervals or DAY/TIME intervals. PO a Cee eee Or eae eee sae CR eC Qe ele Fev fot east eo StudentID INT PRIMARY KEY, FirstName VARCHAR(5®), ee em en es)) ds aise Cate PUD ee kn i ecw Le 2) The INSERT INTO statement is used to add new records to a table. INSERT INTO Students (StudentID, FirstName, LastName, Age) VALUES (1, ‘John’, ‘Doe’, 20); 3) The UPDATE statement is used to modify existing records in a table. oy east ame ears Dra aeratt ata a 4) The DROP statement is used to remove an existing database object, such as a table. DROP TABLE Students; 2.2.2 Cursors +” A major problem in embedding SQL statements in a host language like C is that an impedance mismatch occurs because SQL operates on sets of records, whereas languages like C do not cleanly support a set-of-records abstraction. The solution is to essentially provide a mechanism that allows us to retrieve rows one at a time from a relation- this mechanism is called a cursor Wecan declare a cursor on any relation or on any SQL query. Once a cursor is declared, we can * openit (positions the cursor just before the first row) + Fetch thenext row = Move the cursor (to the next raw,to the row after the next n, to the first row or previous row etc by specifying additional parameters for the fetch command) * Close the cursor Cursor allows us to retrieve the rows in a table by positioning the cursor at a part icular row and reading its contents. Basic Cursor Definition and Usage Cursors enable us to examine, in the host language program, a collection of rows computed by an Embedded SQL statement: * We usually need to open a cursor if the embedded statement is a SELECT. we can avoid opening a cursor if the answer contains a single row * INSERT, DELETE and UPDATE statements require no cursor. some variants of DELETE and UPDATE use a cursor. Examples: ’) Find the name and age of a sailor, specified by assigning a value to the host variable c_sid, declared earlier EXEC SQL SELECT s.sname,s.age sname, :<_age FROM Sailaor s sid; Properties of Cursors The general form of a cursor declaration is: DECLARE cursorname [INSENSITIVE] [SCROLL] CURSOR [WITH HOLD] FOR some query [ORDER BY order-item-list ] [FOR READ ONLY | FOR UPDATE ] A cursor can be declared to be a read-only cursor (FOR READ ONLY) or updatable cursor (FOR UPDATE).If it is updatable, simple variants of the UPDATE and DELETE commands allow us to update or delete the row on which the cursor is positioned. For example, if sinfo is an updatable cursor and open, we can — execute the following statement: UPDATE Sailors S SET S.rating = S.rating -1 WHERE CURRENT of sinfo; A cursor is updatable by default unless it is a scrollable or insensitive cursor in which case it is read- only by default. 1.2.2 Introduction to Triggers in SQL gS A trigger is a procedure that runs automatically when a certain event occurs in the DBMS. In many cases it is convenient to specify the type of action to be taken when certain events occur and when certain conditions are satisfied. The CREATE TRIGGER statement is used to implement such actions in SQL. General form: CREATE TRIGGER BEFORE | AFTER | FOR EACH ROW |FOR EACH STATEMENT WHEN () | Atrigger has three components 1. Event: When this event happens, the trigger is activated « Three event types : Insert, Update, Delete © Two triggering times: Before the event After the event Page 18 2. Condition (optional): If the condition is true, the trigger executes, otherwise skipped 3. Action: The actions performed by the trigger When the Event occurs and Condition is true, execute the Action Create Trigger EmpSal After Insert or Update On Employee Inside “When”, the “new” and For Each Row “old” should not have “:" When (new.salary >150,000) —_— Begin if (:new.salary < 100,000) ... End; Inside the trigger body, they should have “:” 2.6 STORED PROCEDURES a Stored procedure is a set of logical group of SQL statements which are grouped to perform a specific task. Benefits : + reduces the amount of information transfer between client and database server + Compilation step is required only once when the stored procedure is created. Then after it does not require recompilation before executing unless it is modified and reutilizes the same execution plan whereas the SQL statements need to be compiled every time whenever it is sent for execution even if we send the same SQL statement every time + It helps in re usability of the SQL code because it can be used by multiple users and by multiple clients since we need to just call the stored procedure instead of writing the same SQL statement every time. It helps in reducing the development time Page ds Syntax: Create or replace procedure [(argi datatype, ara2 datatype)] Isis Begin Exception End procedurename; 2.6.1 Creating a Simple Stored Procedure Consider the following schema: Student{usn:string,sname:string) Let us now write a stored procedure to retrieve the count of students with sname ‘Akshay’ create or replace procedure ss is stu_cnt int; begin select count(*) into stu_cnt from students where sname='AKSHAY'; dbms_output.put_line('the count of student is :' || stu_cnt); end ss; oO 1.2.1 Specifying General Constraints as Assertions in SQL \ QO Assertions are used to specify additional types of constraints outside scope of built-in relational model constraints. In SQL, users can specify general constraints via declarative assertions, using the CREATE ASSERTION statement of the DDL.Each assertion is given a constraint name and is specified via a condition similar to the WHERE clause of an SQL query. General form : CREATE ASSERTION CHECK () For the assertion to be satisfied, the condition specified after CHECK clause must return true. For example, to specify the constraint that the salary of an employee must not be greater than the salary of the manager of the department that the employee works for in SQL, we can write the following assertion: CREATE ASSERTION SALARY_CONSTRAINT CHECK ( NOT EXISTS ( SELECT * FROM EMPLOYEE E, EMPLOYEE M, DEPARTMENT D WHERE E.Salary>M.Salary AND E.Dno=D.Dnumber AND D.Mgr_ssn=M.Ssn ) ); iy! .2.2 Introduction to Triggers in SQL A trigger is a procedure that runs automatically when a certain event occurs in the DBMS. In many cases It Is convenient to specify the type of action to be taken when certain events occur and when certain conditions are satisfied. The CREATE TRIGGER statement is used to implement such actions in SQL. General form: CREATE TRIGGER BEFORE | AFTER | FOR EACH ROW |FOR EACH STATEMENT WHEN () A vigger has three components 1. Event: When this event happens, the trigger is activated * Three event types : Insert, Update, Delete * Two triggering times: Before the event After the event Page 18 2. Condition (optional): If the condition is true, the trigger executes, otherwise skipped 3. Action: The actions performed by the trigger When the Event occurs and Condition is true, execute the Action \ 43 Views (Virtual Tables) in SQL 1.3.1 Concept of a View in SQL A view in SQL terminology is a single table that is derived from other tables. other tables can be base tables or previously defined views. A view does not necessarily exist in physical form; it is considered to be a virtual table, in contrast to base tables, whose tuples are always physically stored in the database. This limits the possible update operations that can be applied to views, but it does not provide any limitations on querying a view. We can think of a view as a way of specifying a table that we need to reference frequently, even though it may not exist physically. For example, referring to the COMPANY database, we may frequently issue queries that retrieve the employee name and the project names that the employee works on. Rather than having to specify the join of the three tables EMPLOYEE,WORKS_ON, and PROJECT every time we issue this query, we can define a view that is specified as the result of these joins. Then we can issue queries on the view, which are specified as single table retrievals rather than as retrievals involving two joins on three tables. We call the EMPLOYEE,WORKS_ON, and PROJECT tables the defining tables of the view. 1.1.7 Aggregate Functions in SQL Aggregate functions are used to summarize information from multiple tuples into a single-tuple summary. A number of built-in aggregate functions exist: COUNT, SUM, MAX, MIN, and AVG. The ‘COUNT function returns the number of tuples or values as specified in a query. The functions SUM, MAX, MIN, and AVG can be applied ta a set or multiset of numeric values and return, respectively, the sum, maximum value, minimum value, and average (mean) of those values. These functions can be used in the SELECTclause or in a HAVING clause (which we introduce later). The functions MAX and MIN can also be used with attributes that have nonnumeric domains if the domain values have a total ordering among one another. Examples 1. Find the sum of the salaries of all employees, the maximum salary, the minimum salary, and the average salary. SELECT SUM (Salary), MAX (Salary), MIN (Salary), AVG (Salary) FROM EMPLOYEE; 2. Find the sum of the salaries of all employees of the ‘Research’ department, as well as the ‘Maximum salary, the minimum salary, and the average salary in this department. SELECT SUM (Salary), MAX (Salary), MIN (Salary), AVG (Salary) FROM (EMPLOYEE JOIN DEPARTMENT ON Dno=Dnumber) WHERE Dname="Research’; 3. Count the number of distinct salary values in the database. ‘SELECT COUNT (DISTINCT Salary) FROM EMPLOYEE; Page 10 4. To retrieve the names of all employees who have two or more dependents SELECT Lname, Fname FROM EMPLOYEE WHERE ( SELECT COUNT (*) FROM DEPENDENT WHERE Ssn=Essn } >= 2; VX ‘An SQL join clause combines records from two or more tables in a database. It creates a set that can be saved as a table or used as is. A JOIN is a means for combining fields from two tables by using values common to each. SQL specifies four types of JOIN 1. INNER, 2. OUTER 3. EQUDOIN and 4, NATURAL JOIN 1.1.6 Joined Tables in SQL and Outer Joins INNER JOIN An inner join is the most common join operation used in applications and can be regarded as the default join-type. Inner join creates a new result table by combining column values of two tables (A and B) based upon the join- predicate (the condition). The result of the join can be defined as the outcome of first taking the Cartesian product (or Cross join) of all records in the tables (combining every record in table A with every record in table B)—then return all records which satisfy the join predicate Example: SELECT * FROM employee INNER JOIN department ON employee.dno = depart ment.cnumber; EQUNOIN and NATURAL JOIN An EQUNOIN is a specific type of comparator-based join that uses only equality comparisons in the join-predicate. Using other comparison operators (such as <) disqualifies a join as an equijoin. NATURAL JOIN is a type of EQUDOIN where the join predicate arises implicitly by comparing all columns in both tables that have the same column-names in the joined tables. The resulting joined table contains only one column for each pair of equally named columns. SELECT Fname, Lname, Address FROM EMPLOYEE|NATURAL JOIN] DEPARTMENT WHERE Dname="‘Research; OUTER JOIN An outer join does not require each record in the two joined tables to have a matching record. The joined table retains each record-even if no other matching record exists. Quter joins subdivide further into «Left outer joins «Right outer joins «Full outer joins No implicit join-notation for outer joins exists in standard SQL. >» LEFT OUTER JOIN » Every tuple in left table must appear in result > If no matching tuple Padded with NULL values for attributes of right table OBA: SELECT E.Lname AS Employee_name, S.Lname AS Supenisor_name er ee FROM EMPLOYEE AS E, EMPLOYEE AS S result; an EMPLOYEE tuple al . hose valve, WHERE «= ESupataer 3.5m Taser sum (ella woimea o If the wer requires that all be included, OBB: SELECT E.Lname AS Employee_name, Poe S.Lname AS Supervisor_name ae EMPLOYEE AS EJLEFT OUTER JOINJEMPLOYEE AS S [ON| E.Super_ssn=S.Ssn); FROM 2.3. An Introduction to JDBC Embedded SQL enables the integration of SQL with a general-purpose programming language. A DBMS-specific preprocessor transforms the Embedded SQL statements into function calls in the host language. The details of this translation vary across DBMSs, and therefore even though the source code can be compiled to work with different DBMSs, the final executable works only with one specific DBMS. ODBC and JDBC, short for Open DataBase Connectivity and Java DataBase Connectivit y, also enable the integration of SQL with a general-purpose programming language. = In contrast to Embedded SQL, ODBC and JDBC allow a single executable to access different DBMSs Without recompilation. Page 35 = While Embedded SQL is DBMS-independent only at the source code level, applications using ODBC or JDBC are DBMS-independent at the source code level and at the level of the executable * In addition, using ODBC or JDBC, an application can access not just one DBMS but several different ones simultaneously = ODBC and JDBC achieve portability at the level of the executable by introducing an extra level of indirection = All direct interaction with a specific DBMS happens through a DBMS-specific driver. A driver is a software program that translates the ODBC or JDBC calls into DBMS-specific calls. Drivers are loaded dynamically on demand since the DBMSs the application is going to access are known only at run-time. Available drivers are registered with a driver manager a driver does not necessarily need to interact with a DBMS that understands SQL. It is sufficient that the driver translates the SQL commands from the application into equivalent commands that the DBMS understands. 2.3.1 Architecture The architecture of JDBC has four main components: = Application = Driver manager = Drivers = Data sources Page 36 Application ® initiates and terminates the connection with a data source = sets transaction boundaries, submits SQL statements and retrieves the results Driver manager " Load JDBC drivers and pass JDBC function calls fram the application ta the correct driver = Handles JDBC initialization and information calls from the applications and can log all function calls = Performs some rudimentary error checking Drivers = Establishes the connection with the data source = Submits requests and returns request results = Translates data, error formats, and error codes from a form that is specific to the data source into the JDBC standard 2.5 SQLJ: SQL-JAVA \ SQL) enables applications programmers to embed SQL statements in Java code in a that is compatible with the Java design philosophy Example: SQLI code fragment that selects records from the Books table that match a given author. String title; Float price; String author; #q] iterator Books (String title, Float price); Books books; #sql books = { SELECT title, price INTO :title, :price FROM Books WHERE author = :author i while (books.next()) { ‘System.out.printin(books.title() + ", " + books.price()); } books.clase() ; All SQLI statements have the special prefix #sql. In SQLJ, we retrieve the results of SQL queries with iterator objects, which are basically cursors. An iterator is an instance of an iterator class. Usage of an iterator in SQLI goes through five steps: 1. Declare the Iterator Class: In the preceding code, this happened through the statement #sql iterator Books (String title, Float price); This statement creates a new Java class that we can use to instantiate objects. 2. Instantiate an Iterator Object from the New Iterator Class: We instantiated our iterator in the statement Books books;. 3, Initialize the Iterator Using a SQL Statement: In our example, this happens through the statement #sql books 4, _Iteratively, Read the Rows From the Iterator Object: This step is very similar to reading rows through a ResultSet object in JDBC. 5. Closethe Iterator Object.

You might also like