* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download What will happen if we run count(*) with limit statement? It will return
Microsoft Access wikipedia , lookup
Relational algebra wikipedia , lookup
Oracle Database wikipedia , lookup
Serializability wikipedia , lookup
Entity–attribute–value model wikipedia , lookup
Concurrency control wikipedia , lookup
Ingres (database) wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Clusterpoint wikipedia , lookup
Open Database Connectivity wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
Relational model wikipedia , lookup
Database model wikipedia , lookup
What will happen if we run count(*) with limit statement? It will return empty result set. You wrote a search engine that should retrieve 10 results at a time, but at the same time you’d like to know how many rows there’re total. How do you display that to the user? SELECT SQL_CALC_FOUND_ROWS name FROM alarm_employee LIMIT 1,10; SELECT FOUND_ROWS(); Note that FOUND_ROWS does not pay attention to the LIMITs you specified and always returns the total number of rows affected by query. If you don't use SQL_CALC_FOUND_ROWS FOUND_ROWS() will return only count of fetched record not whole. What does this query mean: SELECT e.id, e.name FROM alarm_employee e LEFT JOIN alarm_user USING (id) ? It is equivalent to SELECT e.id, e.name FROM alarm_employee e LEFT JOIN alarm_user u ON u.id = e.id How do you find out which auto increment was assigned on the last insert? SELECT LAST_INSERT_ID() like INSERT INTO `newmd5`.`test` (`id`, `name`, `mail`) VALUES (NULL, 'One', '[email protected]'); SELECT last_insert_id(); It will return 0 if auto increment field not found. How can you see all indexes defined for a table? SHOW INDEX FROM alarm_employee; How do you add three minutes to a date? SELECT ADDDATE(CURdate(), INTERVAL 3 MINUTE) FROM alarm_employee; What’s the difference between Unix timestamps and MySQL timestamps? Internally Unix timestamps are stored as 32-bit integers, while MySQL timestamps are stored in a similar manner, but represented in readable YYYY-MM-DD HH:MM:SS format. What are ENUMs used for in MySQL? You can limit the possible values that go into the table. CREATE TABLE months (month ENUM ‘January’, ‘February’, ‘March’,…); INSERT months VALUES (’April’); What’s the default port for MySQL Server? 3306 How do you change a password for an existing user via mysqladmin? mysqladmin -u root -p password "newpassword" Explain advantages of InnoDB over MyISAM? Row-level locking, transactions, foreign key constraints and crash recovery. Explain advantages of MyISAM over InnoDB? Much more conservative approach to disk space management - each MyISAM table is stored in a separate file, which could be compressed then with myisamchk if needed. With InnoDB the tables are stored in tablespace, and not much further optimization is possible. All data except for TEXT and BLOB can occupy 8,000 bytes at most. No full text indexing is available for InnoDB. TRhe COUNT(*)s execute slower than in MyISAM due to tablespace complexity. What does myisamchk do? It compressed the MyISAM tables, which reduces their disk usage. What are HEAP tables in MySQL? HEAP tables are in-memory. They are usually used for high-speed temporary storage. No TEXT or BLOB fields are allowed within HEAP tables. You can only use the comparison operators = and <=>. HEAP tables do not support AUTO_INCREMENT. Indexes must be NOT NULL. What are CSV tables? Those are the special tables, data for which is saved into comma-separated values files. They cannot be indexed. What happens when the column is set to AUTO INCREMENT and you reach the maximum value for that table? It stops incrementing. It does not overflow to 0 to prevent data losses, but further inserts are going to produce an error, since the key has been used already. Difference between FLOAT, DOUBLE and REAL? FLOATs store floating point numbers with 8 place accuracy and take up 4 bytes. DOUBLEs store floating point numbers with 16 place accuracy and take up 8 bytes. REAL is a synonym of FLOAT for now. What is PHP's MySQL Extension? This is the original extension designed to allow you to develop PHP applications that interact with a MySQL database. The mysql extension provides a procedural interface and is intended for use only with MySQL versions older than 4.1.3. This extension can be used with versions of MySQL 4.1.3 or newer, but not all of the latest MySQL server features will be available. What is PHP's mysqli Extension? The mysqli extension, or as it is sometimes known, the MySQL improved extension, was developed to take advantage of new features found in MySQL systems versions 4.1.3 and newer. The mysqli extension is included with PHP versions 5 and later. The mysqli extension has a number of benefits, the key enhancements over the mysql extension being: * Object-oriented interface * Support for Prepared Statements * Support for Multiple Statements * Support for Transactions * Enhanced debugging capabilities • Embedded server support • API supports Stored Procedures How to Convert float to int in MySQL? With type casting - CAST() function SELECT name FROM table; O/P: 21.45 SELECT CAST(name AS UNSIGNED INTEGER ) FROM table O/P: 21 mysqli is the object-oriented version of mysql library functions. Index in MySQL? Indexes help us retrieve data from tables quicker. It is same as creating a index page for any books, which allow us to locate which pages contain needed information, and then go to that page directly. Syntax to create index: CREATE INDEX "INDEX_NAME" ON "TABLE_NAME" (COLUMN_NAME); We can also create index for more than one column CREATE INDEX "INDEX_NAME" ON "TABLE_NAME" (COL1, COL2); The generally accepted method is to place a prefix, such as "IDX_", When a index is created, it first sorts the data and then it assigns a ROWID for each row. VIEW IN SQL? The CREATE VIEW statement creates a new view, or replaces an existing one if the OR REPLACE clause is given. If the view does not exist, CREATE OR REPLACE VIEW is the same as CREATE VIEW. If the view does exist,CREATE OR REPLACE VIEW is the same as ALTER VIEW. CREATE VIEW v AS SELECT * FROM alarm_employee; To edit view we can use create or replace ... Reason that an INSERT / UPDATE statement might cause an error instead of executing correctly? The INSERT statement was attempting to insert a record into a view that was created from more than one table (Like with JOINS). IF you create views with JOIN of two tables and drop any table what will happen? View will not work, it will give error “references invalid table(s) or column(s)” What are the new feature in MySQL5 ? Stored procedures, triggers, views, information_schema etc .. Difference between grant and revoke? grant will give permission to the user on database grant select on int.book to root; By using revoke we can remove the permission revoke select on int.book from vishwas; Difference between grant, revoke and deny? GRANT --- THIS IS ACCESS GARANTED ON PARTICLUR DB OR USER DENY --- THIS IS PARTICLUR USER WAITING FOR ACCESS WHEN COMMETED THE DATA THEN PERMISSION ON DB REVOKE --- THIS STATEMENT USE THE USER HAVE NO PERMISIONS What are the difference between DDL, DML and DCL commands? Data Definition Language (DDL) statements are used to define the database structure or schema. Some examples: o CREATE - to create objects in the database o ALTER - alters the structure of the database o DROP - delete objects from the database o TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed o COMMENT - add comments to the data dictionary o RENAME - rename an object Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples: SELECT - retrieve data from the a database INSERT - insert data into a table UPDATE - updates existing data within a table DELETE - deletes all records from a table, the space for the records remain MERGE - UPSERT operation (insert or update) CALL - call a PL/SQL or Java subprogram EXPLAIN PLAN - explain access path to data LOCK TABLE - control concurrency Data Control Language (DCL) statements. Some examples: o GRANT - gives user's access privileges to database o REVOKE - withdraw access privileges given with the GRANT command Transaction Control (TCL) statements are used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions. o COMMIT - save work done o SAVEPOINT - identify a point in a transaction to which you can later roll back o ROLLBACK - restore database to original since the last COMMIT o SET TRANSACTION - Change transaction options like isolation level and what rollback segment to use Difference between TRUNCATE, DELETE and DROP commands? DELETE: The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire. It doesn’t affect the auto increment value. TRUNCATE: TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUCATE is faster and doesn't use as much undo space as a DELETE. It doesn’t support TRANSACTION. It reset auto increment value. DROP: The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back. DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. Therefore DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back. How can we encrypt and decrypt a data present in a mysql table using mysql? using AES_ENCRYPT() and AES_DECRYPT() What is the maximum length of a table name, database name, and fieldname in MySQL? The following table describes the maximum length for each type of identifier. Identifier Maximum Length (bytes) Database 64 Table 64 Column 64 Index 64 Alias 255 There are some restrictions on the characters that may appear in identifiers: What is the difference between mysql connect and pconnect mysql_connect opens up a database connection every time a page is loaded. mysql_pconnect opens up a connection, and keeps it open across multiple requests. mysql_pconnect uses less resources, because it does not need to establish a database connection every time a page is loaded. Mysql pconnect is used when the site is heavy traffic and mysql connect is used when less traffic Mysql pconnect does not give u per site visitor login Does not give u sessions How can we repain MySQL table? The syntex for repairing MySQL table is : REPAIR TABLE tablename REPAIR TABLE tablename QUICK REPAIR TABLE tablename EXTENDED This command will repaire the table specified If QUICK is given, MySQL will do the repair of only the index tree If EXTENDED is given, it will create index row by row What is diff bet myisam and innodb? There is following difference between MYISAM and InnoDB Engine :1.MYISAM does not support the foreign key constaint and transaction but InnoDB support it 2.MYISAN is faster then the InnoDB but in case of performing the count operation it takes more time then the InnoDB 3.MYISAM occupies less memory space for table rather than InnoDB tables. What are the differences between stored procedure and functions? a. A FUNCTION is always returns a value using the return statement. A PROCEDURE may return one or more values through parameters or may not return at all. b. Functions are normally used for computations where as procedures are normally used for executing business logic. c. A Function returns 1 value only. Procedure can return multiple values (max 1024). d. Stored procedure returns always integer value by default zero. Whereas function returns type could be scalar or table or table values e. Stored procedure is precompiled execution plan where as functions are not. f. A function can call directly by SQL statement like select func_name from dual while procedure cannot. g.Stored procedure has the security and reduces the network traffic and also we can call stored procedure in any no. of applications at a time. h. A Function can be used in the SQL Queries while a procedure cannot be used in SQL queries .that cause a major difference b/w function and procedures. there are 3 main differences between sp and function. 1 sp takes input,output parameters, function takes only input parameters. 2 temparary variables required to store return values of sp. in functions temparary variables will be optinale. 3 sp can not be called directly into DML statements , functions can be called directly into DML statements. Stored procedures are a set of actions already written and stored inside the database for acheiving a particular task where as functions are general database objects which are used for general purpose programming 1) functions are used for computations where as procedures can be used for performing business logic 2) functions MUST return a value, procedures need not be. 3) you can have DML(insert, update, delete) statements in a function. But, you cannot call such a function in a SQL query..eg: suppose, if u have a function that is updating a table.. you can't call that function in any sql query.select myFunction(field) from sometable; will throw error. 4) function parameters are always IN, no OUT is possible In many instances you can accomplish the same task using either a stored procedure or a function. Both functions and stored procedures can be custom defined and part of any application. Functions, on the other hand, are designed to send their output to a query or TSQL statement. For example, User Defined Functions (UDFs) can run an executable file from SQL SELECT or an action query, while Stored Procedures (SPROC) use EXECUTE or EXEC to run. Both are instantiated using CREATE FUNCTION. To decide between using one of the two, keep in mind the fundamental difference between them: stored procedures are designed to return its output to the application. A UDF returns table variables, while a SPROC can't return a table variable although it can create a table. Another significant difference between them is that UDFs can't change the server environment or your operating system environment, while a SPROC can. Operationally, when T-SQL encounters an error the function stops, while T-SQL will ignore an error in a SPROC and proceed to the next statement in your code (provided you've included error handling support). You PL/SQL Program Units Description All data stored on behalf of stored PL/SQL program units (that is, procedures, functions, packages, and triggers) resides in the SYSTEM tablespace. If the database contains many of these program units, then the database administrator must provide the space the units need in the SYSTEM tablespace. Introduction to Transactions A transaction is a logical unit of work that contains one or more SQL statements. A transaction is an atomic unit. The effects of all the SQL statements in a transaction can be either all committed (applied to the database) or all rolled back (undone from the database). A transaction begins with the first executable SQL statement. A transaction ends when it is committed or rolled back, either explicitly with a COMMIT or ROLLBACK statement or implicitly when a DDL statement is issued. To illustrate the concept of a transaction, consider a banking database. When a bank customer transfers money from a savings account to a checking account, the transaction can consist of three separate operations: Decrement the savings account Increment the checking account Record the transaction in the transaction journal Oracle must allow for two situations. If all three SQL statements can be performed to maintain the accounts in proper balance, the effects of the transaction can be applied to the database. However, if a problem such as insufficient funds, invalid account number, or a hardware failure prevents one or two of the statements in the transaction from completing, the entire transaction must be rolled back so that the balance of all accounts is correct. Commit Transactions Committing a transaction means making permanent the changes performed by the SQL statements within the transaction. Before a transaction that modifies data is committed, the following has occurred: Oracle has generated undo information. The undo information contains the old data values changed by the SQL statements of the transaction. Oracle has generated redo log entries in the redo log buffer of the SGA. The redo log record contains the change to the data block and the change to the rollback block. These changes may go to disk before a transaction is committed. The changes have been made to the database buffers of the SGA. These changes may go to disk before a transaction is committed. When a transaction is committed, the following occurs: The internal transaction table for the associated undo tablespace records that the transaction has committed, and the corresponding unique system change number (SCN) of the transaction is assigned and recorded in the table. The log writer process (LGWR) writes redo log entries in the SGA's redo log buffers to the redo log file. It also writes the transaction's SCN to the redo log file. This atomic event constitutes the commit of the transaction. Oracle releases locks held on rows and tables. Oracle marks the transaction complete. Rollback of Transactions Rolling back means undoing any changes to data that have been performed by SQL statements within an uncommitted transaction. Oracle uses undo tablespaces (or rollback segments) to store old values. The redo log contains a record of changes. Oracle lets you roll back an entire uncommitted transaction. Alternatively, you can roll back the trailing portion of an uncommitted transaction to a marker called a savepoint. All types of rollbacks use the same procedures: Statement-level rollback (due to statement or deadlock execution error) Rollback to a savepoint Rollback of a transaction due to user request Rollback of a transaction due to abnormal process termination Rollback of all outstanding transactions when an instance terminates abnormally Rollback of incomplete transactions during recovery In rolling back an entire transaction, without referencing any savepoints, the following occurs: Oracle undoes all changes made by all the SQL statements in the transaction by using the corresponding undo tablespace. Oracle releases all the transaction's locks of data. The transaction ends. Savepoints In Transactions You can declare intermediate markers called savepoints within the context of a transaction. Savepoints divide a long transaction into smaller parts. Using savepoints, you can arbitrarily mark your work at any point within a long transaction. You then have the option later of rolling back work performed before the current point in the transaction but after a declared savepoint within the transaction. For example, you can use savepoints throughout a long complex series of updates, so if you make an error, you do not need to resubmit every statement. Savepoints are similarly useful in application programs. If a procedure contains several functions, then you can create a savepoint before each function begins. Then, if a function fails, it is easy to return the data to its state before the function began and re-run the function with revised parameters or perform a recovery action. How Transactions Are Named Name a transaction using the SET TRANSACTION ... NAME statement before you start the transaction. When you name a transaction, you associate the transaction's name with its ID. Transaction names do not have to be unique; different transactions can have the same transaction name at the same time by the same owner. You can use any name that enables you to distinguish the transaction. ACID property related to transactions i.e client server communication is called transaction.A transaction is a sequence of operations performed as a single unit of work.A logical unit of work must exhibit four properties called ACID(Atomicity,Consistency,Isolation and Durability)properties to qualify a transaction. Atomicity:A transaction must be an atomic unit of work.i.e either all of its data modifications are performed ,or none of them is performed. Consistancy:when trasaction completed it must leave all data in a consistant state. Isolated:Modifications made by current transactions must be isolated from the modifications made by other trasaction. Durability: after transaction has completed ,it's effects are permanently in place in the sytem. Indexes Indexes are optional structures associated with tables. Indexes can be created to increase the performance of data retrieval. Just as the index in this manual helps you quickly locate specific information, an Oracle index provides an access path to table data. Views Views are customized presentations of data in one or more tables or other views. A view can also be considered a stored query. Views do not actually contain data. Rather, they derive their data from the tables on which they are based, referred to as the base tables of the views. Clusters Clusters are groups of one or more tables physically stored together because they share common columns and are often used together. Because related rows are physically stored together, disk access time improves. Like indexes, clusters do not affect application design. Whether a table is part of a cluster is transparent to users and to applications. Data stored in a clustered table is accessed by SQL in the same way as data stored in a nonclustered table. Synonyms A synonym is an alias for any table, view, materialized view, sequence, procedure, function, package, type, Java class schema object, user-defined object type, or another synonym. Because a synonym is simply an alias, it requires no storage other than its definition in the data dictionary. Integrity Constraints An integrity constraint is a declarative way to define a business rule for a column of a table. An integrity constraint is a statement about table data that is always true and that follows these rules: The following integrity constraints are supported by Oracle: NOT NULL: Disallows nulls (empty entries) in a table's column. UNIQUE KEY: Disallows duplicate values in a column or set of columns. PRIMARY KEY: Disallows duplicate values and nulls in a column or set of columns. FOREIGN KEY: Requires each value in a column or set of columns to match a value in a related table's UNIQUE or PRIMARY KEY. FOREIGN KEY integrity constraints also define referential integrity actions that dictate what Oracle should do with dependent data if the data it references is altered. CHECK: Disallows values that do not satisfy the logical expression of the constraint. Simple views Simple views can only contain a single base table. Examples: CREATE VIEW emp_view AS SELECT * FROM emp; CREATE VIEW dept20 AS SELECT ename, sal*12 annual_salary FROM emp WHERE deptno = 20; One can perform DML operations directly against simple views. These DML changes are then applied to the view's base table. Complex views Complex views can be constructed on more than one base table. In particular, complex views can contain: join conditions a group by clause a order by clause One cannot perform DML operations against complex views directly. To enable DML operations on complex views one needs to write INSTEAD OF triggers to tell Oracle how the changes relate to the base table(s). Examples: CREATE VIEW sample_complex_view AS SELECT emp.empno, emp.ename, emp.job, emp.deptno, dept.dname, dept.loc FROM emp, dept; CREATE VIEW sample_complex_view AS SELECT emp.empno, emp.ename, emp.job, emp.deptno, dept.dname, dept.loc FROM emp, dept WHERE emp.deptno = dept.deptno; Read-only views Users can only run SELECT and DESC statements against read only views. Examples: READ ONLY clause on a simple view: CREATE VIEW clerk (id_number, person, department, position) AS SELECT empno, ename, deptno, job FROM emp WHERE job = 'CLERK' WITH READ ONLY; READ ONLY clause on a complex view: CREATE VIEW sample_complex_view AS SELECT emp.empno, emp.ename, emp.job, emp.deptno, dept.dname, dept.loc FROM emp, dept WITH READ ONLY; Synonym A synonym is an alternative name (or alias) for an object (like an table or view) in the database. Objects can have many synonyms. Use the CREATE SYNONYM SQL command to create synonyms and the DROP SYNONYM command to remove them. To get a list of synonyms, query the USER_SYNONYMS view. Syntax and examples Create a synonym - make emp an alias for the scott.employees table: CREATE SYNONYM emp FOR scott.employees; Create a public synonym (visible to all DB users): CREATE PUBLIC SYNONYM dual FOR sys.dual; CREATE PUBLIC SYNONYM emp FOR scott.employees; Drop a synonym: DROP SYNONYM emp; Drop a public synonym: DROP PUBLIC SYNONYM emp; List synonyms in the current schema: SELECT synonym_name, table_owner, table_name FROM user_synonyms; Trigger A trigger is a program in a database that gets called each time a row in a table is INSERTED, UPDATED, or DELETED. Triggers allow you to check that any changes are correct, or to fill in missing information before it is COMMITed. Triggers are normally written in PL/SQL or Java. Examples Audit logging: CREATE TABLE t1 (c1 NUMBER); CREATE TABLE audit_log(stamp TIMESTAMP, usr VARCHAR2(30), new_val NUMBER); CREATE TRIGGER t1_trig AFTER INSERT ON t1 FOR EACH ROW BEGIN INSERT INTO audit_log VALUES (SYSTIMESTAMP, USER, :NEW.c1); END; / Prevent certain DML operations: CREATE OR REPLACE TRIGGER t1_trig BEFORE INSERT OR UPDATE OR DELETE ON t1 BEGIN raise_application_error(-20001,'Inserting and updating are not allowed!'); END; / What is stored procedure? In database management systems, an operation that is stored with the database server. Typically, stored procedures are written in SQL. They're especially important for clientserver database systems because storing the procedure on the server side means that it is available to all clients. And when the procedure is modified, all clients automatically get the new version. A stored procedure is a group of Transact-SQL statements compiled into a single execution plan. Stored procedures assist in achieving a consistent implementation of logic across applications. The SQL statements and logic needed to perform a commonly performed task can be designed, coded, and tested once in a stored procedure. Each application needing to perform that task can then simply execute the stored procedure. Coding business logic into a single stored procedure also offers a single point of control for ensuring that business rules are correctly enforced. Stored procedures can also improve performance. Many tasks are implemented as a series of SQL statements. Conditional logic applied to the results of the first SQL statements determines which subsequent SQL statements are executed. If these SQL statements and conditional logic are written into a stored procedure, they become part of a single execution plan on the server. The results do not have to be returned to the client to have the conditional logic applied; all of the work is done on the server. The IF statement in this example shows embedding conditional logic in a procedure to keep from sending a result set to the application: IF (@QuantityOrdered < (SELECT QuantityOnHand FROM Inventory WHERE PartID = @PartOrdered) ) BEGIN -- SQL statements to update tables and process order. END ELSE BEGIN -- SELECT statement to retrieve the IDs of alternate items -- to suggest as replacements to the customer. END Applications do not need to transmit all of the SQL statements in the procedure: they have to transmit only an EXECUTE or CALL statement containing the name of the procedure and the values of the parameters. Stored procedures can also shield users from needing to know the details of the tables in the database. If a set of stored procedures supports all of the business functions users need to perform, users never need to access the tables directly; they can just execute the stored procedures that model the business processes with which they are familiar. An illustration of this use of stored procedures is the SQL Server system stored procedures used to insulate users from the system tables. SQL Server includes a set of system stored procedures whose names usually start with sp_. These system stored procedures support all of the administrative tasks required to run a SQL Server system. You can administer a SQL Server system using the Transact-SQL administration-related statements (such as CREATE TABLE) or the system stored procedures, and never need to directly update the system tables. Stored Procedures and Execution Plans In SQL Server version 6.5 and earlier, stored procedures were a way to partially precompile an execution plan. At the time the stored procedure was created, a partially compiled execution plan was stored in a system table. Executing a stored procedure was more efficient than executing an SQL statement because SQL Server did not have to compile an execution plan completely, it only had to finish optimizing the stored plan for the procedure. Also, the fully compiled execution plan for the stored procedure was retained in the SQL Server procedure cache, meaning that subsequent executions of the stored procedure could use the precompiled execution plan. SQL Server 2000 and SQL Server version 7.0 incorporate a number of changes to statement processing that extend many of the performance benefits of stored procedures to all SQL statements. SQL Server 2000 and SQL Server 7.0 do not save a partially compiled plan for stored procedures when they are created. A stored procedure is compiled at execution time, like any other Transact-SQL statement. SQL Server 2000 and SQL Server 7.0 retain execution plans for all SQL statements in the procedure cache, not just stored procedure execution plans. The database engine uses an efficient algorithm for comparing new Transact-SQL statements with the Transact-SQL statements of existing execution plans. If the database engine determines that a new Transact-SQL statement matches the Transact-SQL statement of an existing execution plan, it reuses the plan. This reduces the relative performance benefit of precompiling stored procedures by extending execution plan reuse to all SQL statements. SQL Server 2000 and SQL Server version 7.0 offer new alternatives for processing SQL statements. For more information, see Query Processor Architecture. Temporary Stored Procedures SQL Server 2000 also supports temporary stored procedures that, like temporary tables, are dropped automatically when you disconnect. Temporary stored procedures are stored in tempdb and are useful when connected to earlier versions of SQL Server. Temporary stored procedures can be used when an application builds dynamic Transact-SQL statements that are executed several times. Rather than have the Transact-SQL statements recompiled each time, you can create a temporary stored procedure that is compiled on the first execution, and then execute the precompiled plan multiple times. Heavy use of temporary stored procedures, however, can lead to contention on the system tables in tempdb. Two features of SQL Server 2000 and SQL Server 7.0 eliminate the need for using temporary stored procedures: Execution plans from prior SQL statements can be reused. This is especially powerful when coupled with the use of the new sp_executesql system stored procedure. Natively support for the prepare/execute model of OLE DB and ODBC without using any stored procedures. A stored procedure is a group of SQL statements that form a logical unit and perform a particular task, and they are used to encapsulate a set of operations or queries to execute on a database server. For example, operations on an employee database (hire, fire, promote, lookup) could be coded as stored procedures executed by application code. Stored procedures can be compiled and executed with different parameters and results, and they may have any combination of input, output, and input/output parameters.. What is left join and right join JOIN: If I do a regular JOIN (with none of the keywords INNER, OUTER, LEFT or RIGHT), then I get all records that match in the appropriate way in the two tables, and records in both incoming tables that do not match are not reported. LEFT JOIN: If I do a LEFT JOIN, I get all records that match in the same way and IN ADDITION I get an extra record for each unmatched record in the left table of the join thus ensuring (in my example) that every PERSON gets a mention RIGHT JOIN: If I do a RIGHT JOIN, I get all the records that match and IN ADDITION I get an extra record for each unmatched record in the right table of the join - in my example, that means that each property gets a mention even if we don't have seller details INNER JOIN n OUTER JOIN: An INNER JOIN does a full join, just like the first example, and the word OUTER may be added after the word LEFT or RIGHT in the last two examples - it's provided for ODBC compatibility and doesn't add an extra capabilities Explain the difference between a FUNCTION, PROCEDURE and PACKAGE. A function and procedure are the same in that they are intended to be a collection of PL/SQL code that carries a single task. While a procedure does not have to return any values to the calling application, a function will return a single value. A package on the other hand is a collection of functions and procedures that are grouped together based on their commonality to a business function or application. How can you rebuild an index? ALTER INDEX <index_name> REBUILD; Auto increment CREATE SEQUENCE seq_person MINVALUE 1 START WITH 1 INCREMENT BY 1 CACHE 10 What is a deadlock in SQL ? Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire a lock on the other’s piece. Each process would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. SQL Server detects deadlocks and terminates one user’s process. What is candidate key, alternate key, composite key in SQL ? A candidate key is one that can identify each row of a table uniquely.Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys.A key formed by combining at least two or more columns is called composite key. What is the difference between a “where” clause and a “having” clause in SQL ? “Where” Clause in SQL is a kind of restiriction statement. You use where clause to restrict all the data from DB.Where clause is using before result retrieving. But Having clause is using after retrieving the data.Having clause is a kind of filtering command from the selected data. What is “normalization”? “Denormalization”? Why do you sometimes want to denormalize? Normalizing data means eliminating redundant information from a table and organizing the data so that future changes to the table are easier. Denormalization means allowing redundancy in a table. The main benefit of denormalization is improved performance with simplified data retrieval and manipulation. This is done by reduction in the number of joins needed for data processing. How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables? One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships.One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships.Many-toMany relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table. Can a view based on another view? Yes. What are the advantages of views? - Provide an additional level of table security, by restricting access to a predetermined set of rows and columns of a table. - Hide data complexity. - Simplify commands for the user. - Present the data in a different perspective from that of the base table. - Store complex queries. What is clusters ? Group of tables physically stored together because they share common columns and are often used together is called Cluster. How do I call stored procedures from PHP? The following example shows how to call a stored procedure and return a value. The stored procedure is assumed to have been previously created: create procedure proc1(p1 IN number, p2 OUT number) as begin p2 := p1 + 10; end; The PHP code is: <?php // Connect to database $conn = oci_connect("hr", "hrpwd", "localhost/XE"); if (!$conn) { echo "Connection failed."; exit; } // Call database procedure $in_var = 10; $stid = oci_parse($conn, "begin proc1(:bind1, :bind2); end;"); oci_bind_by_name($stid, ":bind1", $in_var); oci_bind_by_name($stid, ":bind2", $out_var, 32); // 32 is the return length oci_execute($stid); echo "Procedure returned value: " . $out_var; // Logoff from Oracle oci_free_statement($stid) oci_close($conn); ?> PL/SQL PL/SQL blocks that specify procedures and functions can be grouped into packages. A package is similar to a module and has an interface and an implementation part. Oracle offers several predefined packages, for example, input/output routines, file handling, job scheduling etc. Another important feature of PL/SQL is that it offers a mechanism to process query results in a tuple-oriented way, that is, one tuple at a time. For this, cursors are used. In summary, the major goals of PL/SQL are to • increase the expressiveness of SQL, • process query results in a tuple-oriented way, • optimize combined SQL statements, • develop modular database application programs, • reuse program code, and • reduce the cost for maintaining and changing applications. the structure of a PL/SQL looks as follows (brackets [ ] enclose optional parts): [<Block header>] [declare <Constants> <Variables> <Cursors> <User defined exceptions>] begin <PL/SQL statements> [exception <Exception handling>] end; The block header specifies whether the PL/SQL block is a procedure, a function, or a package. If no header is specified, the block is said to be an anonymous PL/SQL block. DECLARATION in PL/SQL declare hire date date; /* implicit initialization with null */ job title varchar2(80) := ’Salesman’; Instead of specifying a data type, one can also refer to the data type of a table column (socalled anchored declaration). For example, EMP.Empno%TYPE refers to the data type of the column Empno in the relation EMP. Instead of a single variable, a record can be declared that can store a complete tuple from a given table (or query result). For example, the data type DEPT%ROWTYPE specifies a record suitable to store all attribute values of a complete row from the table DEPT. Such records are typically used in combination with a cursor. A field in a record can be accessed using <record name>.<column name>, for example, DEPT.Deptno. CURSOR A cursor is basically a pointer to a query result and is used to read attribute values of selected tuples into variables. A cursor typically is used in combination with a loop construct such that each tuple read by the cursor can be processed individually. Processing Cursors: open <cursor name> [(<list of parameters>)] ; fetch <cursor name> into <list of variables>; close <cursor name>; The example below illustrates how a cursor is used together with a continuous loop: declare cursor emp cur is select * from EMP; emp rec EMP%ROWTYPE; emp sal EMP.SAL%TYPE; begin open emp cur; loop fetch emp cur into emp rec; exit when emp cur%NOTFOUND; emp sal := emp rec.sal; <sequence of statements> end loop; close emp cur; ... end; If want to relate with single column of any table, normal select statement can also be used instead of cursor for sal rec in (select SAL + COMM total from EMP) loop ...; end loop; The following PL/SQL block performs the following modifications: All employees having ’KING’ as their manager get a 5% salary increase. declare manager EMP.MGR%TYPE; cursor emp cur (mgr no number) is select SAL from EMP where MGR = mgr no for update of SAL; begin select EMPNO into manager from EMP where ENAME = ’KING’; for emp rec in emp cur(manager) loop update EMP set SAL = emp rec.sal * 1.05 where current of emp cur; end loop; commit; end; Procedures and Functions PL/SQL provides sophisticated language constructs to program procedures and functions as stand-alone PL/SQL blocks. They can be called from other PL/SQL blocks, other procedures and functions. The syntax for a procedure definition is create [or replace] procedure <procedure name> [(<list of parameters>)] is <declarations> begin <sequence of statements> [exception <exception handling routines>] end [<procedure name>]; A function can be specified in an analogous way create [or replace] function <function name> [(<list of parameters>)] return <data type> is ... The optional clause or replace re-creates the procedure/function. A procedure can be deleted using the command drop procedure <procedure name> (drop function <function name>). A parameter is specified as follows: <parameter name> [IN | OUT | IN OUT] <data type> [{ := | DEFAULT} <expression>] The optional clauses IN, OUT, and IN OUT specify the way in which the parameter is used. The default mode for a parameter is IN. IN means that the parameter can be referenced inside the procedure body, but it cannot be changed. OUT means that a value can be assigned to the parameter in the body, but the parameter’s value cannot be referenced. IN OUT allows both assigning values to the parameter and referencing the parameter. Typically, it is sufficient to use the default mode for parameters. The subsequent procedure is used to increase the salary of all employees who work in the department given by the procedure’s parameter. The percentage of the salary increase is given by a parameter, too. create procedure raise salary(dno number, percentage number DEFAULT 0.5) is cursor emp cur (dept no number) is select SAL from EMP where DEPTNO = dept no for update of SAL; empsal number(8); begin open emp cur(dno); - - Here dno is assigned to dept no loop fetch emp cur into empsal; exit when emp cur%NOTFOUND; update EMP set SAL = empsal _ ((100 + percentage)/100) where current of emp cur; end loop; close emp cur; commit; end raise salary; This procedure can be called from the SQL*Plus shell using the command execute raise salary(10, 3); If the procedure is called only with the parameter 10, the default value 0.5 is assumed as specified in the list of parameters in the procedure definition. If a procedure is called from a PL/SQL block, the keyword execute is omitted. Functions Functions have the same structure as procedures. The only difference is that a function returns a value whose data type (unconstrained) must be specified. Example: create function get dept salary(dno number) return number is all sal number; begin all sal := 0; for emp sal in (select SAL from EMP where DEPTNO = dno and SAL is not null) loop all sal := all sal + emp sal.sal; end loop; return all sal; end get dept salary; In order to call a function from the SQL*Plus shell, it is necessary to first define a variable to which the return value can be assigned. In SQL*Plus a variable can be defined using the command variable <variable name> <data type>;, for example, variable salary number. The above function then can be called using the command execute :salary := get dept salary(20); Note that the colon “:” must be put in front of the variable. Packages It is essential for a good programming style that logically related blocks, procedures, and functions are combined into modules, and each module provides an interface which allows users and designers to utilize the implemented functionality.A package consists of a package specification and a package body. Syntaxcreate package manage_employee as -- package specification function hire_emp (name varchar2, job varchar2, mgr number, hiredate date, sal number, comm number default 0, deptno number) return number; procedure fire_emp (emp_id number); procedure raise_sal (emp_id number, sal_incr number); end manage_employee; create package body manage_employee as function hire_emp (name varchar2, job varchar2, mgr number, hiredate date, sal number, comm number default 0, deptno number) return number is -- Insert a new employee with a new employee Id new_empno number(10); begin select emp_sequence.nextval into new_empno from dual; sert into emp values(new_empno, name, job, mgr, hiredate, sal, comm, deptno); return new_empno; end hire_emp; procedure fire_emp(emp_id number) is -- deletes an employee from the table EMP begin delete from emp where empno = emp_id; if SQL%NOTFOUND then -- delete statement referred to invalid emp_id raise_application_error(-20011, ’Employee with Id ’ || to_char(emp_id) || ’ does not exist.’); end if; end fire_emp; procedure raise_sal(emp_id number, sal_incr number) is -- modify the salary of a given employee begin update emp set sal = sal + sal_incr where empno = emp_id; if SQL%NOTFOUND then raise_application_error(-20012, ’Employee with Id ’ || to_char(emp_id) || ’ does not exist’); end if; end raise_sal; end manage_employee; Remark: In order to compile and execute the above package, it is necessary to create first the required sequence (help sequence): create sequence emp sequence start with 8000 increment by 10; Below some of the most important procedures of this package are listed: Procedure name DBMS OUTPUT.ENABLE DBMS OUTPUT.DISABLE DBMS OUTPUT.PUT(<string>) DBMS OUTPUT.PUT LINE(<string>) line marker DBMS OUTPUT.NEW LINE Remark enables output disables output appends (displays) <string> to output buffer appends <string> to output buffer and appends a newdisplays a new-line marker Before strings can be displayed on the screen, the output has to be enabled either using the procedure DBMS OUTPUT.ENABLE or using the SQL*Plus command set serveroutput on (before the procedure that produces the output is called). TRIGGERS It is automatically called by the database system whenever a certain modification (event) occurs on that table. Modifications on a table may include insert, update, and delete operations DELIMITER $$ CREATE TRIGGER trig_gvars_gfirst BEFORE UPDATE ON gvars FOR EACH ROW BEGIN IF NEW.name NOT LIKE 'g%' THEN SET NEW.name = 1 / 0; END IF; END $$ create or replace trigger emp check after insert or delete or update on EMP for each row begin if inserting then <PL/SQL block> end if ; if updating then <PL/SQL block> end if ; if deleting then <PL/SQL block> end if ; end; Basically, the line "SET NEW.name = 1 / 0;" will occur and force an error any time the constraint is not satisfied. That seems to be the best way to cause the insertions not to happen. Quite dirty -- but it beats just getting ignored by the database engine. This also doesn't work if you're updating through FOREIGN KEY actions, such as CASCADE or UPDATE, as TRIGGERs are not called for these actions.