InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
What is Pattern Matching in SQL? |
|
Answer» SQL pattern matching provides for pattern search in data if you have no clue as to what that word should be. This kind of SQL query uses wildcards to match a string pattern, rather than writing the exact word. The LIKE operator is used in CONJUNCTION with SQL Wildcards to fetch the required information.
The % wildcard matches zero or more characters of any type and can be used to define wildcards both before and after the pattern. Search a student in your database with FIRST name beginning with the letter K: SELECT *FROM studentsWHERE first_name LIKE 'K%'
Use the NOT keyword to select records that don't match the pattern. This query returns all students whose first name does not begin with K. SELECT *FROM studentsWHERE first_name NOT LIKE 'K%'
Search for a student in the database where he/she has a K in his/her first name. SELECT *FROM studentsWHERE first_name LIKE '%Q%'
The _ wildcard matches exactly one character of any type. It can be used in conjunction with % wildcard. This query fetches all students with letter K at the third position in their first name. SELECT *FROM studentsWHERE first_name LIKE '__K%'
The _ wildcard plays an important role as a LIMITATION when it matches exactly one character. It limits the length and position of the matched results. For example - SELECT * /* Matches first names with three or more letters */FROM studentsWHERE first_name LIKE '___%'SELECT * /* Matches first names with exactly four characters */FROM studentsWHERE first_name LIKE '____' |
|
| 2. |
How to create empty tables with the same structure as another table? |
|
Answer» Creating empty TABLES with the same structure can be done smartly by fetching the records of ONE table into a new table using the INTO operator while fixing a WHERE CLAUSE to be false for all records. Hence, SQL prepares the new table with a duplicate structure to accept the fetched records but since no records GET fetched due to the WHERE clause in action, nothing is inserted into the new table. SELECT * INTO Students_copyFROM Students WHERE 1 = 2; |
|
| 3. |
What is a Recursive Stored Procedure? |
|
Answer» A stored procedure that calls itself until a BOUNDARY condition is reached, is called a recursive stored procedure. This recursive function helps the programmers to DEPLOY the same set of code several times as and when required. Some SQL programming languages limit the recursion depth to prevent an infinite loop of procedure calls from causing a stack overflow, which slows down the system and may lead to system crashes. DELIMITER $$ /* Set a new delimiter => $$ */CREATE PROCEDURE calctotal( /* Create the procedure */ IN number INT, /* Set Input and OUPUT variables */ OUT TOTAL INT) BEGINDECLARE score INT DEFAULT NULL; /* Set the default value => "score" */SELECT awards FROM achievements /* Update "score" via SELECT query */WHERE ID = number INTO score;IF score IS NULL THEN SET total = 0; /* Termination condition */ELSECALL calctotal(number+1); /* Recursive call */SET total = total + score; /* Action after recursion */END IF;END $$ /* End of procedure */DELIMITER ; /* Reset the delimiter */ |
|
| 4. |
What is a Stored Procedure? |
|
Answer» A STORED procedure is a subroutine available to applications that access a relational database management SYSTEM (RDBMS). Such procedures are stored in the database data dictionary. The sole disadvantage of stored procedure is that it can be executed nowhere except in the database and occupies more MEMORY in the database server. It also provides a sense of security and FUNCTIONALITY as users who can't access the data DIRECTLY can be granted access via stored procedures. DELIMITER $$CREATE PROCEDURE FetchAllStudents()BEGINSELECT * FROM myDB.students;END $$DELIMITER ; |
|
| 5. |
What is Collation? What are the different types of Collation Sensitivity? |
|
Answer» Collation refers to a set of rules that determine how data is sorted and compared. Rules defining the correct character SEQUENCE are used to sort the character data. It INCORPORATES OPTIONS for specifying CASE sensitivity, accent marks, kana character types, and character width. Below are the different types of collation sensitivity:
|
|
| 6. |
What is User-defined function? What are its various types? |
|
Answer» The user-defined functions in SQL are like functions in any other PROGRAMMING language that accept parameters, perform complex calculations, and return a value. They are written to use the logic repetitively WHENEVER required. There are two types of SQL user-defined functions:
|
|
| 7. |
What are Aggregate and Scalar functions? |
|
Answer» An AGGREGATE function performs OPERATIONS on a collection of values to return a single scalar value. Aggregate functions are often used with the GROUP BY and HAVING CLAUSES of the SELECT statement. Following are the widely used SQL aggregate functions:
Note: All aggregate functions described above ignore NULL values except for the COUNT function. A scalar function returns a single value based on the input value. Following are the widely used SQL scalar functions:
|
|
| 8. |
What is the difference between DELETE and TRUNCATE statements? |
|
Answer» The TRUNCATE command is used to delete all the rows from the table and FREE the SPACE containing the table. |
|
| 9. |
What is the difference between DROP and TRUNCATE statements? |
|
Answer» If a table is dropped, all things associated with the tables are dropped as well. This INCLUDES - the RELATIONSHIPS defined on the table with other tables, the integrity checks and constraints, ACCESS privileges and other grants that the table has. To create and use the table again in its original form, all these relations, checks, constraints, privileges and relationships need to be REDEFINED. However, if a table is truncated, none of the above problems exist and the table RETAINS its original structure. |
|
| 10. |
What are the TRUNCATE, DELETE and DROP statements? |
|
Answer» DELETE statement is USED to delete rows from a table. DELETE FROM CandidatesWHERE CandidateId > 1000;TRUNCATE COMMAND is used to delete all the rows from the table and free the space containing the table. TRUNCATE TABLE Candidates;DROP command is used to remove an object from the database. If you drop a table, all the rows in the table are deleted and the table structure is removed from the database. DROP TABLE Candidates; Write a SQL statement to wipe a table 'Temporary' from MEMORY. Check Write a SQL QUERY to remove FIRST 1000 records from table 'Temporary' based on 'id'. Check Write a SQL statement to delete the table 'Temporary' while keeping its relations intact. Check |
|
| 11. |
What are the various forms of Normalization? |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Answer» Normal Forms are used to eliminate or reduce redundancy in database tables. The different forms are as follows:
Students Table
As we can observe, the Books Issued field has more than one value per RECORD, and to convert it into 1NF, this has to be resolved into separate individual records for each book issued. Check the following table in 1NF form - Students Table (1st Normal Form)
A relation is in second normal form if it satisfies the conditions for the first normal form and does not contain any partial dependency. A relation in 2NF has no partial dependency, i.e., it has no non-prime attribute that depends on any proper subset of any candidate key of the table. Often, specifying a single column Primary Key is the solution to the problem. Examples - Example 1 - Consider the above example. As we can observe, the Students Table in the 1NF form has a candidate key in the form of [Student, Address] that can UNIQUELY identify all records in the table. The field Books Issued (non-prime attribute) depends partially on the Student field. Hence, the table is not in 2NF. To convert it into the 2nd Normal Form, we will partition the tables into two while specifying a new Primary Key attribute to identify the individual records in the Students table. The Foreign Key constraint will be set on the other table to ensure referential integrity. Students Table (2nd Normal Form)
Books Table (2nd Normal Form)
Example 2 - Consider the following dependencies in relation to R(W,X,Y,Z) WX -> Y [W and X together determine Y] XY -> Z [X and Y together determine Z]Here, WX is the only candidate key and there is no partial dependency, i.e., any proper subset of WX doesn’t determine any non-prime attribute in the relation.
A relation is said to be in the third normal form, if it satisfies the conditions for the second normal form and there is no transitive dependency between the non-prime attributes, i.e., all non-prime attributes are determined only by the candidate keys of the relation and not by any other non-prime attribute. Example 1 - Consider the Students Table in the above example. As we can observe, the Students Table in the 2NF form has a single candidate key Student_ID (primary key) that can uniquely identify all records in the table. The field Salutation (non-prime attribute), however, depends on the Student Field rather than the candidate key. Hence, the table is not in 3NF. To convert it into the 3rd Normal Form, we will once again partition the tables into two while specifying a new Foreign Key constraint to identify the salutations for individual records in the Students table. The Primary Key constraint for the same will be set on the Salutations table to identify each record uniquely. Students Table (3rd Normal Form)
Books Table (3rd Normal Form)
Salutations Table (3rd Normal Form)
Example 2 - Consider the following dependencies in relation to R(P,Q,R,S,T) P -> QR [P together determine C] RS -> T [B and C together determine D] Q -> S T -> PFor the above relation to exist in 3NF, all possible candidate keys in the above relation should be {P, RS, QR, T}.
A relation is in Boyce-Codd Normal Form if satisfies the conditions for third normal form and for every functional dependency, Left-Hand-Side is super key. In other words, a relation in BCNF has non-trivial functional dependencies in form X –> Y, such that X is always a super key. For example - In the above example, Student_ID serves as the sole unique identifier for the Students Table and Salutation_ID for the Salutations Table, thus these tables exist in BCNF. The same cannot be said for the Books Table and there can be SEVERAL books with common Book Names and the same Student_ID. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| 12. |
What is an Alias in SQL? |
|
Answer» An alias is a feature of SQL that is supported by most, if not all, RDBMSs. It is a temporary name assigned to the table or table column for the purpose of a PARTICULAR SQL query. In addition, aliasing can be EMPLOYED as an obfuscation technique to secure the real names of database fields. A table alias is also called a correlation name. An alias is represented explicitly by the AS keyword but in some cases, the same can be performed without it as well. Nevertheless, using the AS keyword is ALWAYS a good practice. SELECT A.emp_name AS "Employee" /* Alias using AS keyword */B.emp_name AS "Supervisor"FROM employee A, employee B /* Alias without AS keyword */WHERE A.emp_sup = B.emp_id; Write an SQL STATEMENT to select all from table "Limited" with alias "Ltd". Check |
|
| 13. |
List the different types of relationships in SQL. |
Answer»
|
|
| 14. |
What are Entities and Relationships? |
|
Answer» ENTITY: An entity can be a real-world object, EITHER tangible or intangible, that can be easily identifiable. For example, in a college DATABASE, students, professors, WORKERS, departments, and PROJECTS can be referred to as entities. Each entity has some associated properties that provide it an identity. Relationships: Relations or links between entities that have something to do with each other. For example - The employee's table in a company's database can be associated with the salary table in the same database. |
|
| 15. |
What is Cursor? How to use a Cursor? |
|
Answer» A DATABASE CURSOR is a control structure that allows for the traversal of records in a database. Cursors, in addition, facilitates processing after traversal, such as retrieval, addition, and deletion of database records. They can be viewed as a pointer to ONE row in a set of rows. Working with SQL Cursor:
|
|
| 16. |
What are UNION, MINUS and INTERSECT commands? |
|
Answer» The UNION operator combines and returns the result-set RETRIEVED by two or more SELECT statements. Certain conditions need to be met before executing either of the above statements in SQL -
|
|
| 17. |
What are some common clauses used with SELECT query in SQL? |
|
Answer» Some common SQL clauses used in conjuction with a SELECT query are as follows:
|
|
| 18. |
What is the SELECT statement? |
|
Answer» SELECT OPERATOR in SQL is USED to select data from a database. The data RETURNED is STORED in a RESULT table, called the result-set. SELECT * FROM myDB.students; |
|
| 19. |
What is a Subquery? What are its types? |
|
Answer» A subquery is a query WITHIN another query, also known as a nested query or inner query. It is used to RESTRICT or enhance the data to be queried by the main query, thus restricting or enhancing the output of the main query respectively. For example, here we fetch the contact information for students who have enrolled for the maths SUBJECT: SELECT name, email, mob, addressFROM myDb.contactsWHERE roll_no IN ( SELECT roll_no FROM myDb.students WHERE subject = 'Maths');There are two types of subquery - Correlated and Non-Correlated.
|
|
| 20. |
What is a Query? |
|
Answer» A query is a request for DATA or information from a database table or combination of tables. A database query can be either a select query or an ACTION query. SELECT FNAME, lname /* select query */FROM myDb.studentsWHERE student_id = 1;UPDATE myDB.students /* action query */SET fname = 'Captain', lname = 'America'WHERE student_id = 1; |
|
| 21. |
What is Data Integrity? |
|
Answer» Data INTEGRITY is the assurance of accuracy and consistency of data over its entire life-cycle and is a critical ASPECT of the design, implementation, and usage of any SYSTEM which stores, PROCESSES, or retrieves data. It also defines integrity constraints to enforce business rules on the data when it is entered into an APPLICATION or a database. |
|
| 22. |
What is the difference between Clustered and Non-clustered index? |
|
Answer» As EXPLAINED above, the differences can be BROKEN down into three small factors -
|
|
| 23. |
What is an Index? Explain its different types. |
|
Answer» A database index is a data structure that provides a quick lookup of data in a column or columns of a table. It enhances the speed of operations accessing data from a database table at the cost of additional writes and memory to MAINTAIN the index data structure. CREATE INDEX index_name /* Create Index */ON table_name (column_1, column_2);DROP INDEX index_name; /* Drop Index */There are different types of indexes that can be created for different purposes:
Unique indexes are indexes that help maintain data integrity by ensuring that no two rows of data in a table have identical key values. Once a unique index has been defined for a table, uniqueness is enforced whenever keys are ADDED or changed within the index. CREATE UNIQUE INDEX myIndexON students (enroll_no);Non-unique indexes, on the other hand, are not used to enforce CONSTRAINTS on the tables with which they are associated. Instead, non-unique indexes are used solely to improve query performance by maintaining a sorted order of data values that are used frequently.
Clustered indexes are indexes whose order of the rows in the database corresponds to the order of the rows in the index. This is why only one clustered index can EXIST in a given table, whereas, multiple non-clustered indexes can exist in the table. The only difference between clustered and non-clustered indexes is that the database manager attempts to keep the data in the database in the same order as the corresponding keys appear in the clustered index. Clustering indexes can improve the performance of most query operations because they provide a linear-access path to data stored in the database. Write a SQL statement to create a UNIQUE INDEX "my_index" on "my_table" for fields "column_1" & "column_2". Check |
|
| 24. |
What is a Cross-Join? |
|
Answer» CROSS join can be defined as a cartesian product of the two tables INCLUDED in the join. The table after join contains the same number of rows as in the cross-product of the number of rows in the two tables. If a WHERE clause is used in cross join then the query will work like an INNER JOIN. SELECT stu.name, sub.subject FROM students AS stuCROSS JOIN subjects AS sub; Write a SQL statement to CROSS JOIN 'table_1' with 'table_2' and fetch 'col_1' from table_1 & 'col_2' from table_2 respectively. Do not USE alias. CHECK Write a SQL statement to perform SELF JOIN for 'Table_X' with alias 'Table_1' and 'Table_2', on columns 'Col_1' and 'Col_2' respectively. Check |
|
| 25. |
What is a Self-Join? |
|
Answer» A self JOIN is a case of REGULAR join where a table is joined to itself BASED on some RELATION between its own column(s). Self-join uses the INNER JOIN or LEFT JOIN clause and a table alias is used to assign different names to the table within the query. SELECT A.emp_id AS "Emp_ID",A.emp_name AS "Employee",B.emp_id AS "Sup_ID",B.emp_name AS "Supervisor"FROM employee A, employee BWHERE A.emp_sup = B.emp_id; |
|
| 26. |
What is a Join? List its different types. |
|
Answer» The SQL Join clause is used to combine RECORDS (rows) from two or more tables in a SQL database based on a related column between the two. There are four different TYPES of JOINs in SQL:
|
|
| 27. |
What is a Foreign Key? |
|
Answer» A FOREIGN KEY comprises of single or collection of fields in a table that essentially refers to the PRIMARY KEY in another table. Foreign key CONSTRAINT ensures referential INTEGRITY in the relation between two tables. |
|
| 28. |
What is a UNIQUE constraint? |
|
Answer» A UNIQUE CONSTRAINT ensures that all values in a column are different. This provides uniqueness for the column(s) and helps identify each row uniquely. Unlike primary key, there can be multiple unique constraints defined PER table. The code syntax for UNIQUE is quite SIMILAR to that of PRIMARY KEY and can be used interchangeably. CREATE TABLE Students ( /* Create table with a single field as unique */ ID INT NOT NULL UNIQUE Name VARCHAR(255));CREATE TABLE Students ( /* Create table with multiple fields as unique */ ID INT NOT NULL LastName VARCHAR(255) FirstName VARCHAR(255) NOT NULL CONSTRAINT PK_Student UNIQUE (ID, FirstName));ALTER TABLE Students /* SET a column as unique */ADD UNIQUE (ID);ALTER TABLE Students /* Set multiple COLUMNS as unique */ADD CONSTRAINT PK_Student /* Naming a unique constraint */UNIQUE (ID, FirstName); |
|
| 29. |
What is a Primary Key? |
|
Answer» The PRIMARY KEY constraint uniquely identifies each row in a table. It must contain UNIQUE values and has an implicit NOT NULL constraint. |
|
| 30. |
What are Tables and Fields? |
|
Answer» A table is an organized COLLECTION of data stored in the form of ROWS and COLUMNS. Columns can be categorized as vertical and rows as horizontal. The columns in a table are CALLED fields while the rows can be referred to as RECORDS. |
|
| 31. |
What is the difference between SQL and MySQL? |
|
Answer» SQL is a standard language for retrieving and manipulating STRUCTURED DATABASES. On the contrary, MySQL is a relational database MANAGEMENT system, like SQL Server, Oracle or IBM DB2, that is used to manage SQL databases. |
|
| 32. |
What is SQL? |
|
Answer» SQL STANDS for Structured Query Language. It is the STANDARD language for relational database management systems. It is especially useful in handling ORGANIZED data comprised of entities (variables) and RELATIONS between different entities of the data. |
|
| 33. |
What is RDBMS? How is it different from DBMS? |
|
Answer» RDBMS stands for Relational Database Management System. The key difference here, compared to DBMS, is that RDBMS STORES data in the form of a collection of tables, and relations can be defined between the common fields of these tables. Most modern database management SYSTEMS like MySQL, MICROSOFT SQL Server, ORACLE, IBM DB2, and Amazon Redshift are based on RDBMS. |
|
| 34. |
What is DBMS? |
|
Answer» DBMS stands for DATABASE Management System. DBMS is a system software responsible for the creation, RETRIEVAL, updation, and management of the database. It ensures that our data is consistent, organized, and is easily accessible by SERVING as an interface between the database and its end-users or APPLICATION software. |
|
| 35. |
What is Database? |
|
Answer» A DATABASE is an organized collection of data, stored and retrieved digitally from a remote or local computer system. Databases can be vast and COMPLEX, and such databases are developed using fixed DESIGN and modeling APPROACHES. |
|