Interview Questions and answers on Database Basics
1. What is DBMS ?
The database management system is a collection of programs that enables user to store, retrieve, update and delete information from a database.
2. What is RDBMS ?
Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model. Data from relational database can be accessed or reassembled in many different ways without having to reorganize the database tables. Data from relational database can be accessed using an API , Structured Query Language (SQL).
3. What is SQL ?
Structured Query Language(SQL) is a language designed specifically for communicating with databases. SQL is an ANSI (American National Standards Institute) standard.
4. What are the different type of SQL’s statements ?
1. DDL – Data Definition Language DDL is used to define the structure that holds the data. For example, Create, Alter, Drop and Truncate table. 2. DML– Data Manipulation Language DML is used for manipulation of the data itself. Typical operations are Insert, Delete, Update and retrieving the data from the table. Select statement is considered as a limited version of DML, since it can't change data in the database. But it can perform operations on data retrieved from DBMS, before the results are returned to the calling function. 3. DCL– Data Control Language DCL is used to control the visibility of data like granting database access and set privileges to create tables etc. Example - Grant, Revoke access permission to the user to access data in database.
5. What are the Advantages of SQL ?
1. SQL is not a proprietary language used by specific database vendors. Almost every major DBMS supports SQL, so learning this one language will enable programmers to interact with any database like ORACLE, SQL ,MYSQL etc. 2. SQL is easy to learn. The statements are all made up of descriptive English words, and there aren't that many of them. 3. SQL is actually a very powerful language and by using its language elements you can perform very complex and sophisticated database operations.
6. what is a field in a database ?
A field is an area within a record reserved for a specific piece of data. Examples: Employee Name, Employee ID etc
7. What is a Record in a database ?
A record is the collection of values / fields of a specific entity: i.e. an Employee, Salary etc.
8. What is a Table in a database ?
A table is a collection of records of a specific type. For example, employee table, salary table etc.
9. What is a database transaction?
Database transaction takes database from one consistent state to another. At the end of the transaction the system must be in the prior state if the transaction fails or the status of the system should reflect the successful completion if the transaction goes through.
10. What are properties of a transaction? Expect this SQL Interview Questions as a part of an any interview, irrespective of your experience. Properties of the transaction can be summarized as ACID Properties.
1. Atomicity A transaction consists of many steps. When all the steps in a transaction gets completed, it will get reflected in DB or if any step fails, all the transactions are rolled back. 2. Consistency The database will move from one consistent state to another, if the transaction succeeds and remain in the original state, if the transaction fails. 3. Isolation Every transaction should operate as if it is the only transaction in the system. 4. Durability Once a transaction has completed successfully, the updated rows/records must be available for all other transactions on a permanent basis.
11. What is a Database Lock ?
Database lock tells a transaction, if the data item in questions is currently being used by other transactions.
12. What are the type of locks ?
1. Shared Lock When a shared lock is applied on data item, other transactions can only read the item, but can't write into it. 2. Exclusive Lock When an exclusive lock is applied on data item, other transactions can't read or write into the data item.
Database Normalization Interview Questions
13. What are the different type of normalization?
In database design, we start with one single table, with all possible columns. A lot of redundant data would be present since it’s a single table. The process of removing the redundant data, by splitting up the table in a well defined fashion is called normalization.1. First Normal Form (1NF) A relation is said to be in first normal form if and only if all underlying domains contain atomic values only. After 1NF, we can still have redundant data. 2. Second Normal Form (2NF) A relation is said to be in 2NF if and only if it is in 1NF and every non key attribute is fully dependent on the primary key. After 2NF, we can still have redundant data. 3. Third Normal Form (3NF) A relation is said to be in 3NF, if and only if it is in 2NF and every non key attribute is non-transitively dependent on the primary key.
Database Keys and Constraints SQL Interview Questions
14. What is a primary key?
A primary key is a column whose values uniquely identify every row in a table. Primary key values can never be reused. If a row is deleted from the table, its primary key may not be assigned to any new rows in the future. To define a field as primary key, following conditions had to be met : 1. No two rows can have the same primary key value. 2. Every row must have a primary key value 3. The primary key field cannot be null 4. Values in primary key columns can never be modified or updated
15. What is a Composite Key ?
A Composite primary key is a type of candidate key, which represents a set of columns whose values uniquely identify every row in a table. For example - if "Employee_ID" and "Employee Name" in a table is combined to uniquely identify a row its called a Composite Key.
16. What is a Composite Primary Key ?
A Composite primary key is a set of columns whose values uniquely identify every row in a table. What it means is that, a table which contains composite primary key will be indexed based on the columns specified in the primary key. This key will be referred in Foreign Key tables. For example - if the combined effect of columns, "Employee_ID" and "Employee Name" in a table is required to uniquely identify a row, its called a Composite Primary Key. In this case, both the columns will be represented as primary key.
17. What is a Foreign Key ?
When a "one" table's primary key field is added to a related "many" table in order to create the common field which relates the two tables, it is called a foreign key in the "many" table. For example, the salary of an employee is stored in salary table. The relation is established via foreign key column “Employee_ID_Ref” which refers “Employee_ID” field in the Employee table.
18. What is a Unique Key ?
Unique key is same as primary with the difference being the existence of null. Unique key field allows one value as NULL value.
SQL Insert, Update and Delete Commands Interview Questions
19. Define SQL Insert Statement ?
SQL INSERT statement is used to add rows to a table. For a full row insert, SQL Query should start with “insert into “ statement followed by table name and values command, followed by the values that need to be inserted into the table. The insert can be used in several ways: 1. To insert a single complete row. 2. To insert a single partial row.
20. Define SQL Update Statement ?
SQL Update is used to update data in a row or set of rows specified in the filter condition. The basic format of an SQL UPDATE statement is, Update command followed by table to be updated and SET command followed by column names and their new values followed by filter condition that determines which rows should be updated.
21. Define SQL Delete Statement ?
SQL Delete is used to delete a row or set of rows specified in the filter condition. The basic format of an SQL DELETE statement is, DELETE FROM command followed by table name followed by filter condition that determines which rows should be updated.
22. What are wild cards used in database for Pattern Matching ?
SQL Like operator is used for pattern matching. SQL ‘Like’ command takes more time to process. So before using “like” operator, consider suggestions given below on when and where to use wild card search.
1) Don’t overuse wild cards. If another search operator will do, use it instead.
2) When you do use wild cards, try not to use them at the beginning of the search pattern, unless absolutely necessary. Search patterns that begin with wild cards are the slowest to process.
3) Pay careful attention to the placement of the wild card symbols. If they are misplaced, you might not return the data you intended.
SQL Joins Interview Questions and answers
23. Define Join and explain different type of joins?
Another frequently asked SQL Interview Questions on Joins. In order to avoid data duplication, data is stored in related tables. Join keyword is used to fetch data from related tables. "Join" return rows when there is at least one match in both table. Type of joins are Right Join Return all rows from the right table, even if there are no matches in the left table. Outer Join Left Join Return all rows from the left table, even if there are no matches in the right table. Full Join Return rows when there is a match in one of the tables.
24. What is Self-Join?
Self-join is query used to join a table to itself. Aliases should be used for the same table comparison.
25. What is Cross Join?
Cross Join will return all records where each row from the first table is combined with each row from the second table.
Database Views Interview Questions
26. What is a view?
The views are virtual tables. Unlike tables that contain data, views simply contain queries that dynamically retrieve data when used.
27. What is a materialized view?
Materialized views are also a view but are disk based. Materialized views get updates on specific duration, base upon the interval specified in the query definition. We can index materialized view.
28. What are the advantages and disadvantages of views in a database?
Advantages: 1. Views don't store data in a physical location. 2. The view can be used to hide some of the columns from the table. 3. Views can provide Access Restriction, since data insertion, update and deletion is not possible with the view. Disadvantages: 1. When a table is dropped, associated view become irrelevant. 2. Since the view is created when a query requesting data from view is triggered, its a bit slow. 3. When views are created for large tables, it occupies more memory.\
Stored Procedures and Triggers Interview Questions
29. What is a stored procedure?
Stored Procedure is a function which contains a collection of SQL Queries. The procedure can take inputs , process them and send back output.
30. What are the advantages a stored procedure?
Stored Procedures are precomplied and stored in the database. This enables the database to execute the queries much faster. Since many queries can be included in a stored procedure, round trip time to execute multiple queries from source code to database and back is avoided.
31. What is a trigger?
Database triggers are sets of commands that get executed when an event(Before Insert, After Insert, On Update, On delete of a row) occurs on a table, views.
32. Explain the difference between DELETE , TRUNCATE and DROP commands?
Once delete operation is performed, Commit and Rollback can be performed to retrieve data. Once the truncate statement is executed, Commit and Rollback statement cannot be performed. Where condition can be used along with delete statement but it can't be used with truncate statement. Drop command is used to drop the table or keys like primary,foreign from a table.
34. What is Union, minus and Interact commands?
MINUS operator is used to return rows from the first query but not from the second query. INTERSECT operator is used to return rows returned by both the queries.
35.What is SQL?
SQL stands for structured query language. It is a database language used for database creation, deletion, fetching rows and modifying rows etc. sometimes it is pronounced as se-qwell.
36.When SQL appeared?
It appeared in 1974.
37. What are the usages of SQL?
- To execute queries against a database
- To retrieve data from a database
- To inserts records in a database
- To updates records in a database
- To delete records from a database
- To create new databases
- To create new tables in a database
- To create views in a database
38. Does SQL support programming?
No, SQL doesn’t have loop or Conditional statement. It is used like commanding language to access databases.
39. What are the subsets of SQL?
- Data definition language (DDL)
- Data manipulation language (DML)
- Data control language (DCL)
40. What is data definition language?
Data definition language(DDL) allows you to CREATE, ALTER and DELETE database objects such as schema, tables, view, sequence etc.
41. What is data manipulation language?
Data manipulation language makes user able to access and manipulate data. It is used to perform following operations.
- Insert data into database
- Retrieve data from the database
- Update data in the database
- Delete data from the database
42. What is data control language?
Data control language allows you to control access to the database. It includes two commands GRANT and REVOKE.
GRANT: to grant specific user to perform specific task.
REVOKE: to cancel previously denied or granted permissions.
43. What are the type of operators available in SQL?
- Arithmetic operators
- Logical operators
- Comparison operator
45. What is the SQL query to display current date?
There is a built in function in SQL called GetDate() which is used to return current timestamp.
46. Which types of join is used in SQL widely?
The knowledge of JOIN is very necessary for an interviewee. Mostly used join is INNER JOIN and (left/right) OUTER JOIN.
47. What is “TRIGGER” in SQL?
Trigger allows you to execute a batch of SQL code when an insert, update or delete command is executed against a specific table.
Actually triggers are special type of stored procedures that are defined to execute automatically in place or after data modifications.
48. What is self join and what is the requirement of self join?
Self join is often very useful to convert a hierarchical structure to a flat structure. It is used to join a table to itself as like if that is the second table.
49. What are set operators in SQL?
Union, intersect or minus operators are called set operators.
50. What is a constraint? Tell me about its various levels.
Constraints are representators of a column to enforce data entity and consistency. There are two levels :
- column level constraint
- table level constraint
53. What is the difference between DELETE and TRUNCATE statement in SQL?
The main differences between SQL DELETE and TRUNCATE statements are given below:
|1)||DELETE is a DML command.||TRUNCATE is a DDL command.|
|2)||We can use WHERE clause in DELETE command.||We cannot use WHERE clause with TRUNCATE|
|3)||DELETE statement is used to delete a row from a table||TRUNCATE statement is used to remove all the rows from a table.|
|4)||DELETE is slower than TRUNCATE statement.||TRUNCATE statement is faster than DELETE statement.|
|5)||You can rollback data after using DELETE statement.||It is not possible to rollback after using TRUNCATE statement.|
54.What is ACID property in database?
ACID property is used to ensure that the data transactions are processed reliably in a database system.
A single logical operation of a data is called transaction.
ACID is an acronym for Atomicity, Consistency, Isolation, Durability.
Atomicity: it requires that each transaction is all or nothing. It means if one part of the transaction fails, the entire transaction fails and the database state is left unchanged.
Consistency: the consistency property ensure that the data must meet all validation rules. In simple words you can say that your transaction never leaves your database without completing its state.
Isolation: this property ensure that the concurrent property of execution should not be met. The main goal of providing isolation is concurrency control.
Durability: durability simply means that once a transaction has been committed, it will remain so, come what may even power loss, crashes or errors.
57. Write SQL Query to display current date.
Answer : SQL has built in function called GetDate() which returns current timestamp. This will work in Microsoft SQL Server, other vendors like Oracle and MySQL also has equivalent functions.
58.: Write an SQL Query to check whether date passed to Query is date of given format or not.
Answer : SQL has IsDate() function which is used to check passed value is date or not of specified format ,it returns 1(true) or 0(false) accordingly. Remember ISDATE() is a MSSQL function and it may not work on Oracle, MySQL or any other database but there would be something similar.
SELECT ISDATE(‘1/08/13’) AS “MM/DD/YY”;
It will return 0 because passed date is not in correct format.
60.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-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table.
It will be a good idea to read up a database designing fundamentals text book.
61. What’s the difference between a primary key and a unique key?
Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn’t allow NULLs, but nique key allows one NULL only.
62.What are user defined datatypes and when you should go for them?
User defined datatypes let you extend the base SQL Server datatypes by providing a descriptive name, and format to the database. Take for example, in your database, there is a column called Flight_Num which appears in many tables. In all these tables it should be varchar(8). In this case you could create a user defined datatype called Flight_num_type of varchar(8) and use it across all your tables.
63. What is bit datatype and what’s the information that can be stored inside a bit column?
Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server 6.5 bit datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards, bit datatype can represent a third state, which is NULL.
64. Define candidate key, alternate key, composite key
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.
65. What are defaults? Is there a column to which a default can’t be bound?
A default is a value that will be used by a column, if no value is supplied to that column while inserting data. IDENTITY columns and timestamp columns can’t have defaults bound to them. See CREATE DEFUALT in books online.
66. What is a transaction and what are ACID properties?
A transaction is a logical unit of work in which, all the steps must be performed or none. ACID stands for Atomicity, Consistency, Isolation, Durability. These are the properties of a transaction. For more information and explanation of these properties, see SQL Server books online or any RDBMS fundamentals text book.
67. Explain different isolation levels
An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL Server isolation level is Read Committed. Here are the other isolation levels (in the ascending order of isolation): Read Uncommitted, Read Committed, Repeatable Read, Serializable. See SQL Server books online for an explanation of the isolation levels. Be sure to read about SET TRANSACTION ISOLATION LEVEL, which lets you customize the isolation level at the connection level.
68.. What’s the maximum size of a row?
8060 bytes. Don’t be surprised with questions like ‘what is the maximum number of columns per table’. Check out SQL Server books online for the page titled: “Maximum Capacity Specifications”.
69. What is lock escalation?
Lock escalation is the process of converting a lot of low level locks (like row locks, page locks) into higher level locks (like table locks). Every lock is a memory structure too many locks would mean, more memory being occupied by locks. To prevent this from happening, SQL Server escalates the many fine-grain locks to fewer coarse-grain locks. Lock escalation threshold was definable in SQL Server 6.5, but from SQL Server 7.0 onwards it’s dynamically managed by SQL Server.
70. What’s the difference between DELETE TABLE and TRUNCATE TABLE commands?
DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won’t log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back.
71. Explain the storage models of OLAP
Check out MOLAP, ROLAP and HOLAP in SQL Server books online for more infomation.
72. What are constraints? Explain different types of constraints
Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you to create triggers, rule or defaults.
Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY
For an explanation of these constraints see books online for the pages titled: “Constraints” and “CREATE TABLE”, “ALTER TABLE”
73. What is a deadlock and what is a live lock? How will you go about resolving deadlocks?
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.
A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and refuses further shared locks. A livelock also occurs when read transactions monopolize a table or page, forcing a write transaction to wait indefinitely.
74. What is blocking and how would you troubleshoot it?
Blocking happens when one connection from an application holds a lock and a second connection requires a conflicting lock type. This forces the second connection to wait, blocked on the first.
Read up the following topics in SQL Server books online: Understanding and avoiding blocking, Coding efficient transactions.
75. As a part of your job, what are the DBCC commands that you commonly use for database maintenance?
DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC CHECKALLOC, DBCC SHOWCONTIG, DBCC SHRINKDATABASE, DBCC SHRINKFILE etc. But there are a whole load of DBCC commands which are very useful for DBAs. Check out SQL Server books online for more information.
76. What are the different ways of moving data/databases between servers and databases in SQL Server?
There are lots of options available, you have to choose your option depending upon your requirements. Some of the options you have are: BACKUP/RESTORE, dettaching and attaching databases, replication, DTS, BCP, logshipping, INSERT…SELECT, SELECT…INTO, creating INSERT scripts to generate data.
77. Explain different types of BACKUPs available in SQL Server? Given a particular scenario, how would you go about choosing a backup plan?
Types of backups you can create in SQL Sever 7.0+ are Full database backup, differential database backup, transaction log backup, filegroup backup. Check out the BACKUP and RESTORE commands in SQL Server books online. Be prepared to write the commands in your interview. Books online also has information on detailed backup/restore architecture and when one should go for a particular kind of backup.
78. What is database replication? What are the different types of replication you can set up in SQL Server?
Replication is the process of copying/moving data between databases on the same or different servers. SQL Server supports the following types of replication scenarios:
o Snapshot replication
o Transactional replication (with immediate updating subscribers, with queued updating subscribers)
o Merge replication
See SQL Server books online for indepth coverage on replication. Be prepared to explain how different replication agents function, what are the main system tables used in replication etc.
79.What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors?
Cursors allow row-by-row processing of the resultsets.
Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information.
Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip, where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors.
Most of the times, set based operations can be used instead of cursors. Here is an example:
If you have to give a flat hike to your employees using the following criteria:
Salary between 30000 and 40000 — 5000 hike
Salary between 40000 and 55000 — 7000 hike
Salary between 55000 and 65000 — 9000 hike
In this situation many developers tend to use a cursor, determine each employee’s salary and update his salary according to the above formula. But the same can be achieved by multiple update statements or can be combined in a single UPDATE statement as shown below:
UPDATE tbl_emp SET salary =
CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000
WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000
Another situation in which developers tend to use cursors: You need to call a stored procedure when a column in a particular row meets certain condition. You don’t have to use cursors for this. This can be achieved using WHILE loop, as long as there is a unique key to identify each row.
80. Write down the general syntax for a SELECT statements covering all the options
Here’s the basic syntax: (Also checkout SELECT in books online for advanced syntax).
[GROUP BY group_by_expression]
[ORDER BY order_expression [ASC | DESC] ]
81. What is a join and explain different types of joins
Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table.
Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs.OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.
82. Can you have a nested transaction?
Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN and @@TRANCOUNT
83. What is an extended stored procedure? Can you instantiate a COM object by using T-SQL?
An extended stored procedure is a function within a DLL (written in a programming language like C, C++ using Open Data Services (ODS) API) that can be called from T-SQL,just the way we call normal stored procedures using the EXEC statement. See books online to learn how to create extended stored procedures and how to add them to SQL Server.
Yes, you can instantiate a COM (written in languages like VB, VC++) object from T-SQL by using sp_OACreate stored procedure. Also see books online for sp_OAMethod, sp_OAGetProperty, sp_OASetProperty, sp_OADestroy.
84. What is the system function to get the current user’s user id?
USER_ID().Also check out other system functions like USER_NAME(), SYSTEM_USER, SESSION_USER, CURRENT_USER, USER, SUSER_SID(), HOST_NAME().
85. What are triggers? How many triggers you can have on a table? How to invoke a trigger on demand?
Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or DELETE operation takes place on a table.
In SQL Server 6.5 you could define only 3 triggers per table, one for INSERT, one for UPDATE and one for DELETE. From SQL Server 7.0 onwards, this restriction is gone, and you could create multiple triggers per each action. But in 7.0 there’s no way to control the order in which the triggers fire. In SQL Server 2000 you could specify which trigger fires first or fires last using sp_settriggerorder
Triggers can’t be invoked on demand. They get triggered only when an associated action (INSERT, UPDATE, DELETE) happens on the table on which they are defined.
Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers, as constraints are much faster.
Till SQL Server 7.0, triggers fire only after the data modification operation happens. So in a way, they are called post triggers. But in SQL Server 2000 you could create pre triggers also. Search SQL Server 2000 books online for INSTEAD OF triggers.
86. There is a trigger defined for INSERT operations on a table, in an OLTP system. The trigger is written to instantiate a COM object and pass the newly insterted rows to it for some custom processing. What do you think of this implementation? Can this be implemented better?
Instantiating COM objects is a time consuming process and since you are doing it from within a trigger, it slows down the data insertion process. Same is the case with sending emails from triggers. This scenario can be better implemented by logging all the necessary data into a separate table, and have a job which periodically checks this table and does the needful.
87. What is a self join? Explain it with an example
Self join is just like any other join, except that two instances of the same table will be joined in the query. Here is an example: Employees table which contains rows for normal employees as well as managers. So, to find out the managers of all the employees, you need a self join.
CREATE TABLE emp
INSERT emp SELECT 1,2,’Vyas’
INSERT emp SELECT 2,3,’Mohan’
INSERT emp SELECT 3,NULL,’Shobha’
INSERT emp SELECT 4,2,’Shridhar’
INSERT emp SELECT 5,2,’Sourabh’
SELECT t1.empname [Employee], t2.empname [Manager]
FROM emp t1, emp t2
WHERE t1.mgrid = t2.empid
Here’s an advanced query using a LEFT OUTER JOIN that even returns the employees without managers (super bosses)
SELECT t1.empname [Employee], COALESCE(t2.empname, ‘No manager’) [Manager]
FROM emp t1
LEFT OUTER JOIN
t1.mgrid = t2.empid
109.List and explain the different types of
JOIN clauses supported in ANSI-standard SQL.
88.ANSI-standard SQL specifies five types of
JOIN clauses as follows:
INNER JOIN(a.k.a. “simple join”): Returns all rows for which there is at least one match in BOTH tables. This is the default type of join if no specific
JOINtype is specified.
LEFT OUTER JOIN): Returns all rows from the left table, and the matched rows from the right table; i.e., the results will contain all records from the left table, even if the
JOINcondition doesn’t find any matching records in the right table. This means that if the
ONclause doesn’t match any records in the right table, the
JOINwill still return a row in the result for that record in the left table, but with NULL in each column from the right table.
RIGHT OUTER JOIN): Returns all rows from the right table, and the matched rows from the left table. This is the exact opposite of a
LEFT JOIN; i.e., the results will contain all records from the right table, even if the
JOINcondition doesn’t find any matching records in the left table. This means that if the
ONclause doesn’t match any records in the left table, the
JOINwill still return a row in the result for that record in the right table, but with NULL in each column from the left table.
FULL OUTER JOIN): Returns all rows for which there is a match in EITHER of the tables. Conceptually, a
FULL JOINcombines the effect of applying both a
LEFT JOINand a
RIGHT JOIN; i.e., its result set is equivalent to performing a
UNIONof the results of left and right outer queries.
CROSS JOIN: Returns all records where each row from the first table is combined with each row from the second table (i.e., returns the Cartesian product of the sets of rows from the joined tables). Note that a
CROSS JOINcan either be specified using the
CROSS JOINsyntax (“explicit join notation”) or (b) listing the tables in the
FROMclause separated by commas without using a
WHEREclause to supply join criteria (“implicit join notation”).