The most popular SQL Interview Questions and Answers:
Detailed SQL Interview Questions And Answers are as follows-
1. What is Database?
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.
2. What is DBMS?
DBMS stands for Database Management System. DBMS is a system software responsible for the creation, retrieval, updating, 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.
3. What is RDBMS? How is it different from DBMS?
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.
4. What is SQL?
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.
5. What is the difference between SQL and MySQL?
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.
|SQL is a standard language which stands for Structured Query Language based on the English language||MySQL is a database management system.|
|SQL is the core of the relational database which is used for accessing and managing database||MySQL is an RDMS (Relational Database Management System) such as SQL Server, Informix etc.|
6. What are Tables and Fields?
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.
7. What are Constraints in SQL?
Constraints are used to specify the rules concerning data in the table. It can be applied for single or multiple fields in an SQL table during creation of table or after creationg using the ALTER TABLE command. The constraints are:
- NOT NULL– Restricts NULL value from being inserted into a column.
- CHECK – Verifies that all values in a field satisfy a condition.
- DEFAULT– Automatically assigns a default value if no value has been specified for the field.
- UNIQUE– Ensures unique values to be inserted into the field.
- INDEX – Indexes a field providing faster retrieval of records.
- PRIMARY KEY– Uniquely identifies each record in a table.
- FOREIGN KEY– Ensures referential integrity for a record in another table.
8. What is a Primary Key?
The PRIMARY KEY constraint uniquely identifies each row in a table. It must contain UNIQUE values and has an implicit NOT NULL constraint.
A table in SQL is strictly restricted to have one and only one primary key, which is comprised of single or multiple fields (columns).
- A Primary key is a column (or collection of columns) or a set of columns that uniquely identifies each row in the table.
- Uniquely identifies a single row in the table
- Null values not allowed
Example- In the Student table, Stu_ID is the primary key.
CREATE TABLE Students ( /* Create table with a single field as primary key */ ID INT NOT NULL Name VARCHAR(255) PRIMARY KEY (ID)); CREATE TABLE Students ( /* Create table with multiple fields as primary key */ ID INT NOT NULL LastName VARCHAR(255) FirstName VARCHAR(255) NOT NULL, CONSTRAINT PK_Student PRIMARY KEY (ID, FirstName)); ALTER TABLE Students /* Set a column as primary key */ADD PRIMARY KEY (ID); ALTER TABLE Students /* Set multiple columns as primary key */ADD CONSTRAINT PK_Student /*Naming a Primary Key*/PRIMARY KEY (ID, FirstName);
9. What is a UNIQUE constraint?
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);
10. What is a Foreign Key?
A FOREIGN KEY comprises of single or collection of fields in a table that essentially refer to the PRIMARY KEY in another table. Foreign key constraint ensures referential integrity in the relation between two tables.
The table with the foreign key constraint is labelled as the child table, and the table containing the candidate key is labelled as the referenced or parent table.
- Foreign key maintains referential integrity by enforcing a link between the data in two tables.
- The foreign key in the child table references the primary key in the parent table.
- The foreign key constraint prevents actions that would destroy links between the child and parent tables.
CREATE TABLE Students ( /* Create table with foreign key – Way 1 */ ID INT NOT NULL Name VARCHAR(255) LibraryID INT PRIMARY KEY (ID) FOREIGN KEY (Library_ID) REFERENCES Library(LibraryID)); CREATE TABLE Students ( /* Create table with foreign key – Way 2 */ ID INT NOT NULL PRIMARY KEY Name VARCHAR(255) LibraryID INT FOREIGN KEY (Library_ID) REFERENCES Library(LibraryID)); ALTER TABLE Students /* Add a new foreign key */ADD FOREIGN KEY (LibraryID)REFERENCES Library (LibraryID);
11. What is a Join? List its different types.
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:
(INNER) JOIN: Retrieves records that have matching values in both tables involved in the join. This is the widely used join for queries.
SELECT * FROM Table_A JOIN Table_B;SELECT * FROM Table_A INNER JOIN Table_B;
LEFT (OUTER) JOIN: Retrieves all the records/rows from the left and the matched records/rows from the right table.
SELECT * FROM Table_A A LEFT JOIN Table_B B ON A.col = B.col;
RIGHT (OUTER) JOIN: Retrieves all the records/rows from the right and the matched records/rows from the left table.
SELECT * FROM Table_A A RIGHT JOIN Table_B B ON A.col = B.col;
FULL (OUTER) JOIN: Retrieves all the records where there is a match in either the left or right table.
SELECT * FROM Table_A A FULL JOIN Table_B B ON A.col = B.col;
12. What is a Self-Join?
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;
13. What is a Cross-Join?
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 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;
14. What is an Index? Explain its different types.
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 and Non-Unique Index:
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 and Non-Clustered Index:
Clustered indexes are indexes whose order of the rows in the database correspond 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 index can improve the performance of most query operations because they provide a linear-access path to data stored in the database.
15. What is the difference between Clustered and Non-clustered index?
As explained above, the differences can be broken down into three small factors –
- Clustered index modifies the way records are stored in a database based on the indexed column. Non-clustered index creates a separate entity within the table which references the original table.
- Clustered index is used for easy and speedy retrieval of data from the database, whereas, fetching records from the non-clustered index is relatively slower.
- In SQL, a table can have a single clustered index whereas it can have multiple non-clustered indexes.
16. What is Data Integrity?
Data Integrity is the assurance of accuracy and consistency of data over its entire life-cycle, and is a critical aspect to 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.
17. What is a Query?
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;
18. What is a Subquery? What are its types?
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, address FROM myDb.contactsWHERE roll_no IN (SELECT roll_no FROM myDb.students WHERE subject = ‘Maths’);
There are two types of subquery – Correlated and Non-Correlated.
- A correlated subquery cannot be considered as an independent query, but it can refer to the column in a table listed in the FROM of the main query.
- A non-correlated subquery can be considered as an independent query and the output of the subquery is substituted in the main query.
19. What is the SELECT statement?
A 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;
20. What are some common clauses used with SELECT query in SQL?
Some common SQL clauses used in conjuction with a SELECT query are as follows:
- WHEREclause in SQL is used to filter records that are necessary, based on specific conditions.
- ORDER BYclause in SQL is used to sort the records based on some field(s) in ascending (ASC) or descending order (DESC).
SELECT * FROM myDB.students WHERE graduation_year = 2019 ORDER BY studentID DESC;
- GROUP BY clause in SQL is used to group records with identical data and can be used in conjuction with some aggregation functions to produce summarized results from the database.
- HAVING clause in SQL is used to filter records in combination with the GROUP BY clause. It is different from WHERE, since WHERE clause cannot filter aggregated records.
SELECT COUNT(studentId), country FROM myDB.students WHERE country != “INDIA” GROUP BY country HAVING COUNT(studentID) > 5;
21. What are UNION, MINUS and INTERSECT commands?
The UNION operator combines and returns the result-set retrieved by two or more SELECT statements.
The MINUS operator in SQL is used to remove duplicates from the result-set obtained by the second SELECT query from the result-set obtained by the first SELECT query and then return the filtered results from the first.
The INTERSECT clause in SQL combines the result-set fetched by the two SELECT statements where records from one match the other and then returns this intersection of result-sets.
Certain conditions need to be met before executing either of the above statements in SQL –
- Each SELECT statement within the clause must have the same number of columns
- The columns must also have similar data types
- The columns in each SELECT statement should necessarily have the same order
SELECT name FROM Students /* Fetch the union of queries */UNIONSELECT name FROM Contacts; SELECT name FROM Students /* Fetch the union of queries with duplicates*/UNION ALLSELECT name FROM Contacts;SELECT name FROM Students /* Fetch names from students */MINUS /* that aren’t present in contacts */SELECT name FROM Contacts;SELECT name FROM Students /* Fetch names from students */INTERSECT /* that are present in contacts as well */SELECT name FROM Contacts;
22. What is Cursor? How to use a Cursor?
A database cursor is a control structure that allows for 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
- DECLARE a cursor after any variable declaration. The cursor declaration must always be associated with a SELECT Statement.
- Open cursor to initialize the result set. The OPENstatement must be called before fetching rows from the result set.
- FETCH statement to retrieve and move to the next row in the result set.
- Call the CLOSEstatement to deactivate the cursor.
- Finally, use the DEALLOCATEstatement to delete the cursor definition and release the associated resources.
DECLARE @name VARCHAR(50) /* Declare All Required Variables */ DECLARE db_cursor CURSOR FOR /* Declare Cursor Name*/SELECT nameFROM myDB.studentsWHERE parent_name IN (‘Sara’, ‘Ansh’) OPEN db_cursor /* Open cursor and Fetch data into @name */ FETCH nextFROM db_cursorINTO @name CLOSE db_cursor /* Close the cursor and deallocate the resources */DEALLOCATE db_cursor
23. What are Entities and Relationships?
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 table in a company’s database can be associated with the salary table in the same database.
24. List the different types of relationships in SQL.
- One-to-One– This can be defined as the relationship between two tables where each record in one table is associated with the maximum of one record in the other table.
- One-to-Many& Many-to-One – This is the most commonly used relationship where a record in a table is associated with multiple records in the other table.
- Many-to-Many– This is used in cases when multiple instances on both sides are needed for defining a relationship.
- Self Referencing Relationships– This is used when a table needs to define a relationship with itself.
25. What is Alias in SQL?
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;
26. What is a View?
A view in SQL is a virtual table based on the result-set of an SQL statement. A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.
27. What is Normalization and what are the advantages ?
Normalization represents the way of organizing structured data in the database efficiently. It includes the creation of tables, establishing relationships between them, and defining rules for those relationships. Inconsistency and redundancy can be kept in check based on these rules, hence, adding flexibility to the database.
Normalization is the process of organizing data to avoid duplication and redundancy. Some of the advantages are:
- Better Database organization
- More Tables with smaller rows
- Efficient data access
- Greater Flexibility for Queries
- Quickly find the information
- Easier to implement Security
- Allows easy modification
- Reduction of redundant and duplicate data
- More Compact Database
- Ensure Consistent data after modification
28. Explain different types of Normalization.
There are many successive levels of normalization. These are called normal forms. Each consecutive normal form depends on the previous one. The first three normal forms are usually adequate.
- First Normal Form (1NF) – No repeating groups within rows
- Second Normal Form (2NF) – Every non-key (supporting) column value is dependent on the whole primary key.
- Third Normal Form (3NF) – Dependent solely on the primary key and no other non-key (supporting) column value.
29. What is Denormalization?
Denormalization is the inverse process of normalization, where the normalized schema is converted into a schema that has redundant information. The performance is improved by using redundancy and keeping the redundant data consistent. The reason for performing denormalization is the overheads produced in the query processor by an over-normalized structure.
30. What are the TRUNCATE, DELETE and DROP statements?
A DELETE statement is used to delete rows from a table.
DELETE FROM CandidatesWHERE CandidateId > 1000;
A 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 is deleted and the table structure is removed from the database.
DROP TABLE Candidates;
31. What is the difference between DROP and TRUNCATE statements?
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.
32. What is the difference between DELETE and TRUNCATE statements?
The TRUNCATE command is used to delete all the rows from the table and free the space containing the table.
The DELETE command deletes only the rows from the table based on the condition given in the where clause or deletes all the rows from the table if no condition is specified. But it does not free the space containing the table.
33. What are Aggregate and Scalar functions?
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:
- AVG() – Calculates the mean of a collection of values.
- COUNT() – Counts the total number of records in a specific table or view.
- MIN() – Calculates the minimum of a collection of values.
- MAX() – Calculates the maximum of a collection of values.
- SUM() – Calculates the sum of a collection of values.
- FIRST() – Fetches the first element in a collection of values.
- LAST() – Fetches the last element in a collection of values.
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:
- LEN() – Calculates the total length of the given field (column).
- UCASE() – Converts a collection of string values to uppercase characters.
- LCASE() – Converts a collection of string values to lowercase characters.
- MID() – Extracts substrings from a collection of string values in a table.
- CONCAT() – Concatenates two or more strings.
- RAND() – Generates a random collection of numbers of given length.
- ROUND() – Calculates the round off integer value for a numeric field (or decimal point values).
- NOW() – Returns the current data & time.
- FORMAT() – Sets the format to display a collection of values.
34. What is User-defined function? What are its various types?
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:
- Scalar Function: As explained earlier, user-defined scalar functions return a single scalar value.
- Table Valued Functions: User-defined table-valued functions return a table as output.
- Inline: returns a table data type based on a single SELECT statement.
- Multi-statement: returns a tabular result-set but, unlike inline, multiple SELECT statements can be used inside the function body.
35. What is OLTP?
OLTP stands for Online Transaction Processing, is a class of software applications capable of supporting transaction-oriented programs. An essential attribute of an OLTP system is its ability to maintain concurrency. To avoid single points of failure, OLTP systems are often decentralized. These systems are usually designed for a large number of users who conduct short transactions. Database queries are usually simple, require sub-second response times and return relatively few records. Here is an insight into the working of an OLTP system
36. What are the differences between OLTP and OLAP?
OLTP stands for Online Transaction Processing, is a class of software applications capable of supporting transaction-oriented programs. An important attribute of an OLTP system is its ability to maintain concurrency. OLTP systems often follow a decentralized architecture to avoid single points of failure. These systems are generally designed for a large audience of end users who conduct short transactions. Queries involved in such databases are generally simple, need fast response times and return relatively few records. Number of transactions per second acts as an effective measure for such systems.
OLAP stands for Online Analytical Processing, a class of software programs which are characterized by relatively low frequency of online transactions. Queries are often too complex and involve a bunch of aggregations. For OLAP systems, the effectiveness measure relies highly on response time. Such systems are widely used for data mining or maintaining aggregated, historical data, usually in multi-dimensional schemas.
37. What is Collation? What are the different types of Collation Sensitivity?
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:
- Casesensitivity: A and a are treated differently.
- Accentsensitivity: a and á are treated differently.
- Kanasensitivity: Japanese kana characters Hiragana and Katakana are treated differently.
- Widthsensitivity: Same character represented in single-byte (half-width) and double-byte (full-width) are treated differently.
38. What is a Stored Procedure?
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 ;
39. What is a Recursive Stored Procedure?
A stored procedure which 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 */
40. How to create empty tables with the same structure as another table?
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;
41. What is Pattern Matching in SQL?
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.
- Using the % wildcard to perform a simple search
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:
2. SELECT *3. FROM students4. WHERE first_name LIKE ‘K%’
- Omitting the patterns using the NOT keyword
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.
6. SELECT *7. FROM students8. WHERE first_name NOT LIKE ‘K%’
- Matching a pattern anywhere using the % wildcard twice
Search for a student in the database where he/she has a K in his/her first name.
10. SELECT *11. FROM students12. WHERE first_name LIKE ‘%Q%’
- Using the _ wildcard to match pattern at a specific position
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.
14. SELECT *15. FROM students16. WHERE first_name LIKE ‘__K%’
- Matching patterns for specific length
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 –
18. SELECT * /* Matches first names with three or more letters */19. FROM students20. WHERE first_name LIKE ‘___%’21. 22. SELECT * /* Matches first names with exactly four characters */23. FROM students24. WHERE first_name LIKE ‘____’
42. What are the different subsets of SQL?
- DDL (Data Definition Language) – It allows you to perform various operations on the database such as CREATE, ALTER and DELETE objects.
- DML ( Data Manipulation Language) – It allows you to access and manipulate data. It helps you to insert, update, delete and retrieve data from the database.
- DCL ( Data Control Language) – It allows you to control access to the database. Example – Grant, Revoke access permissions.
43. What do you mean by DBMS? What are its different types?
A database is a structured collection of data.
A Database Management System (DBMS) is a software application that interacts with the user, applications and the database itself to capture and analyze data.
A DBMS allows a user to interact with the database. The data stored in the database can be modified, retrieved and deleted and can be of any type like strings, numbers, images etc.
There are two types of DBMS:
- Relational Database Management System: The data is stored in relations (tables). Example – MySQL.
- Non-Relational Database Management System: There is no concept of relations, tuples and attributes. Example – Mongo
44. What do you mean by table and field in SQL?
A table refers to a collection of data in an organised manner in form of rows and columns. A field refers to the number of columns in a table. For example:
Field: Stu Id, Stu Name, Stu Marks
45. What are joins in SQL?
A JOIN clause is used to combine rows from two or more tables, based on a related column between them. It is used to merge two tables or retrieve data from there. There are 4 joins in SQL namely:
- Inner Join
- Right Join
- Left Join
- Full Join
46. What is the difference between CHAR and VARCHAR2 datatype in SQL?
Both Char and Varchar2 are used for characters datatype but varchar2 is used for character strings of variable length whereas Char is used for strings of fixed length. For example, char(10) can only store 10 characters and will not be able to store a string of any other length whereas varchar2(10) can store any length i.e 6,8,2 in this variable.
47. What is the difference between DELETE and TRUNCATE statements?
|DELETE vs TRUNCATE|
|Delete command is used to delete a row in a table.||Truncate is used to delete all the rows from a table.|
|You can rollback data after using delete statement.||You cannot rollback data.|
|It is a DML command.||It is a DDL command.|
|It is slower than truncate statement.||It is faster|
48. What is a Unique key?
- Uniquely identifies a single row in the table.
- Multiple values allowed per table.
- Null values allowed.
49. What do you mean by data integrity?
Data Integrity defines the accuracy as well as the consistency of the data stored in a database. It also defines integrity constraints to enforce business rules on the data when it is entered into an application or a database.
50. What is the difference between clustered and non clustered index in SQL?
The differences between the clustered and non clustered index in SQL are :
- Clustered index is used for easy retrieval of data from the database and its faster whereas reading from non clustered index is relatively slower.
- Clustered index alters the way records are stored in a database as it sorts out rows by the column which is set to be clustered index whereas in a non clustered index, it does not alter the way it was stored but it creates a separate object within a table which points back to the original table rows after searching.
- One table can only have one clustered index whereas it can have many non clustered index.
51. Write a SQL query to display the current date?
In SQL, there is a built-in function called GetDate() which helps to return the current timestamp/date.
52. What are Entities and Relationships?
Entities: A person, place, or thing in the real world about which data can be stored in a database. Tables store data that represents one type of entity. For example – A bank database has a customer table to store customer information. Customer table stores this information as a set of attributes (columns within the table) for each customer.
Relationships: Relation or links between entities that have something to do with each other. For example – The customer name is related to the customer account number and contact information, which might be in the same table. There can also be relationships between separate tables (for example, customer to accounts).
53. What is an Index?
An index refers to a performance tuning method of allowing faster retrieval of records from the table. An index creates an entry for each value and hence it will be faster to retrieve data.
54. Explain different types of index.
There are three types of index namely:
This index does not allow the field to have duplicate values if the column is unique indexed. If a primary key is defined, a unique index can be applied automatically.
This index reorders the physical order of the table and searches based on the basis of key values. Each table can only have one clustered index.
Non-Clustered Index does not alter the physical order of the table and maintains a logical order of the data. Each table can have many nonclustered indexes.
55. What is ACID property in a database?
ACID stands for Atomicity, Consistency, Isolation, Durability. It is used to ensure that the data transactions are processed reliably in a database system.
Atomicity: Atomicity refers to the transactions that are completely done or failed where transaction refers to a single logical operation of a data. It means if one part of any transaction fails, the entire transaction fails and the database state is left unchanged.
Consistency: Consistency ensures that the data must meet all the validation rules. In simple words, you can say that your transaction never leaves the database without completing its state.
Isolation: The main goal of isolation is concurrency control.
Durability: Durability means that if a transaction has been committed, it will occur whatever may come in between such as power loss, crash or any sort of error.
56. What do you mean by “Trigger” in SQL?
Trigger in SQL is are a special type of stored procedures that are defined to execute automatically in place or after data modifications. It allows you to execute a batch of code when an insert, update or any other query is executed against a specific table.
57. What are the different operators available in SQL?
There are three operators available in SQL, namely:
- Arithmetic Operators
- Logical Operators
- Comparison Operators
58. Are NULL values the same as that of zero or a blank space?
A NULL value is not at all same as that of zero or a blank space. NULL value represents a value that is unavailable, unknown, assigned or not applicable whereas a zero is a number and blank space is a character.
59. What is the difference between cross join and natural join?
The cross join produces the cross product or Cartesian product of two tables whereas the natural join is based on all the columns having the same name and data types in both the tables.
60. What is subquery in SQL?
A subquery is a query inside another query where a query is defined to retrieve data or information back from the database. In a subquery, the outer query is called as the main query whereas the inner query is called subquery. Subqueries are always executed first and the result of the subquery is passed on to the main query. It can be nested inside a SELECT, UPDATE or any other query. A subquery can also use any comparison operators such as >,< or =.
61. What are the different types of a subquery?
There are two types of subquery namely, Correlated and Non-Correlated.
Correlated subquery: These are queries which select the data from a table referenced in the outer query. It is not considered as an independent query as it refers to another table and refers the column in a table.
Non-Correlated subquery: This query is an independent query where the output of subquery is substituted in the main query.
62. Write a SQL query to find the names of employees that begin with ‘A’?
To display name of the employees that begin with ‘A’, type in the below command:
SELECT * FROM Table_name WHERE EmpName like ‘A%’;
63. Write a SQL query to get the third highest salary of an employee from employee_table?
SELECT TOP 1 salary
SELECT TOP 3 salary
ORDER BY salary DESC) AS emp
ORDER BY salary ASC;
- What is the need for group functions in SQL?
Group functions work on the set of rows and returns one result per group. Some of the commonly used group functions are: AVG, COUNT, MAX, MIN, SUM, VARIANCE.
65. What is a Relationship and what are they?
Relation or links are between entities that have something to do with each other. Relationships are defined as the connection between the tables in a database. There are various relationships, namely:
- One to One Relationship.
- One to Many Relationship.
- Many to One Relationship.
- Self-Referencing Relationship.
66. How can you insert NULL values in a column while inserting the data?
NULL values can be inserted in the following ways:
- Implicitly by omitting column from column list.
- Explicitly by specifying NULL keyword in the VALUES clause
67. What is the main difference between ‘BETWEEN’ and ‘IN’ condition operators?
BETWEEN operator is used to display rows based on a range of values in a row whereas the IN condition operator is used to check for values contained in a specific set of values.
Example of BETWEEN:
SELECT * FROM Students where ROLL_NO BETWEEN 10 AND 50;
Example of IN:
SELECT * FROM students where ROLL_NO IN (8,15,25);
68. Why are SQL functions used?
SQL functions are used for the following purposes:
- To perform some calculations on the data
- To modify individual data items
- To manipulate the output
- To format dates and numbers
- To convert the data types
69. What is the need of MERGE statement?
This statement allows conditional update or insertion of data into a table. It performs an UPDATE if a row exists, or an INSERT if the row does not exist.
70. What is CLAUSE in SQL?
SQL clause helps to limit the result set by providing a condition to the query. A clause helps to filter the rows from the entire set of records.
For example – WHERE, HAVING clause.
71. What is the difference between ‘HAVING’ CLAUSE and a ‘WHERE’ CLAUSE?
HAVING clause can be used only with SELECT statement. It is usually used in a GROUP BY clause and whenever GROUP BY is not used, HAVING behaves like a WHERE clause.
Having Clause is only used with the GROUP BY function in a query whereas WHERE Clause is applied to each row before they are a part of the GROUP BY function in a query.
72. List the ways in which Dynamic SQL can be executed?
Following are the ways in which dynamic SQL can be executed:
- Write a query with parameters.
- Using EXEC.
- Using sp_executesql.
73. What are the various levels of constraints?
Constraints are the representation of a column to enforce data entity and consistency. There are two levels of a constraint, namely:
- column level constraint
- table level constraint
74. How can you fetch common records from two tables?
You can fetch common records from two tables using INTERSECT. For example:
Select studentID from student. <strong>INTERSECT </strong> Select StudentID from Exam
75. List some case manipulation functions in SQL?
There are three case manipulation functions in SQL, namely:
- LOWER: This function returns the string in lowercase. It takes a string as an argument and returns it by converting it into a lower case. Syntax:
- UPPER: This function returns the string in uppercase. It takes a string as an argument and returns it by converting it into uppercase. Syntax:
- INITCAP: This function returns the string with the first letter in uppercase and rest of the letters in lowercase. Syntax:
76. What are the different set operators available in SQL?
Some of the available set operators are – Union, Intersect or Minus operators.
77. What are aggregate and scalar functions?
Aggregate functions are used to evaluate mathematical calculation and return a single value. These calculations are done from the columns in a table. For example- max(),count() are calculated with respect to numeric.
Scalar functions return a single value based on the input value. For example – UCASE(), NOW() are calculated with respect to a string.
- Name the operator which is used in the query for pattern matching?
LIKE operator is used for pattern matching, and it can be used as -.
- % – It matches zero or more characters.
For example- select * from students where studentname like ‘a%’
_ (Underscore) – it matches exactly one character.
For example- select * from student where studentname like ‘abc_’
79. How can you select unique records from a table?
You can select unique records from a table by using the DISTINCT keyword.
Select DISTINCT studentID from Student
Using this command, it will print unique student id from the table Student.
80. How can you fetch first 5 characters of the string?
There are a lot of ways to fetch characters from a string. For example:
Select SUBSTRING(StudentName,1,5) as studentname from student
81. What is the main difference between SQL and PL/SQL?
SQL is a query language that allows you to issue a single query or execute a single insert/update/delete whereas PL/SQL is Oracle’s “Procedural Language” SQL, which allows you to write a full program (loops, variables, etc.) to accomplish multiple operations such as selects/inserts/updates/deletes.
82. What are Views used for?
A view refers to a logical snapshot based on a table or another view. It is used for the following reasons:
- Restricting access to data.
- Making complex queries simple.
- Ensuring data independence.
- Providing different views of same data.
83. List some advantages and disadvantages of Stored Procedure?
A Stored Procedure can be used as a modular programming which means create once, store and call for several times whenever it is required. This supports faster execution. It also reduces network traffic and provides better security to the data.
The only disadvantage of Stored Procedure is that it can be executed only in the database and utilizes more memory in the database server.
84. List all the types of user-defined functions?
There are three types of user-defined functions, namely:
- Scalar Functions
- Inline Table-valued functions
- Multi-statement valued functions
Scalar returns the unit, variant defined the return clause. Other two types of defined functions return table.
85. What do you mean by Collation?
Collation is defined as a set of rules that determine how data can be sorted as well as compared. Character data is sorted using the rules that define the correct character sequence along with options for specifying case-sensitivity, character width etc.
86. What are the different types of Collation Sensitivity?
Following are the different types of collation sensitivity:
- Case Sensitivity: A and a and B and b.
- Kana Sensitivity: Japanese Kana characters.
- Width Sensitivity: Single byte character and double-byte character.
- Accent Sensitivity.
87. What are Local and Global variables?
These variables can be used or exist only inside the function. These variables are not used or referred to by any other function.
These variables are the variables that can be accessed throughout the program. Global variables cannot be created whenever that function is called.
88. What is Auto Increment in SQL?
Auto increment keyword allows the user to create a unique number to get generated whenever a new record is inserted into the table.
This keyword is usually required whenever PRIMARY KEY is used.
AUTO INCREMENT keyword can be used in Oracle and IDENTITY keyword can be used in SQL SERVER.
89. What is a Datawarehouse?
Datawarehouse refers to a central repository of data where the data is assembled from multiple sources of information. Those data are consolidated, transformed, and made available for mining as well as online processing. Warehouse data also have a subset of data called Data Marts.
90. What are tables in SQL?
The table is a collection of record and its information at a single view.
- What are transactions and their controls?
A transaction can be defined as a sequence task that is performed on databases in a logical manner to gain certain results. Operations like Creating, updating, deleting records performed in the database come from transactions.
here are 4 transaction controls such as
- COMMIT: It is used to save all changes made through the transaction.
- ROLLBACK: It is used to roll back the transaction. All changes made by the transaction are reverted back and the database remains as before.
- SET TRANSACTION: Set the name of the transaction.
- SAVEPOINT: It is used to set the point where the transaction is to be rolled back.
- How many Aggregate functions are available in SQL?
SQL Aggregate functions determine and calculate values from multiple columns in a table and return a single value.
There are 7 aggregate functions in SQL:
- AVG(): Returns the average value from specified columns.
- COUNT(): Returns number of table rows.
- MAX(): Returns the largest value among the records.
- MIN(): Returns smallest value among the records.
- SUM(): Returns the sum of specified column values.
- FIRST(): Returns the first value.
- LAST(): Returns last value.
- Explain the working of SQL Privileges?
SQL GRANT and REVOKE commands are used to implement privileges in SQL multiple user environments. The administrator of the database can grant or revoke privileges to or from users of database objects by using commands like SELECT, INSERT, UPDATE, DELETE, ALL, etc.
GRANT Command: This command is used to provide database access to users other than the administrator.
REVOKE command: This command is used to provide database deny or remove access to database objects.
- How many types of Privileges are available in SQL?
There are two types of privileges used in SQL, such as
- System privilege: System privilege deals with the object of a particular type and provides users the right to perform one or more actions on it. These actions include performing administrative tasks, ALTER ANY INDEX, ALTER ANY CACHE GROUP CREATE/ALTER/DELETE TABLE, CREATE/ALTER/DELETE VIEW, etc.
- Object privilege: This allows to perform actions on an object or object of another user(s) viz. table, view, indexes, etc. Some of the object privileges are EXECUTE, INSERT, UPDATE, DELETE, SELECT, FLUSH, LOAD, INDEX, REFERENCES, etc.
95. What is SQL Injection?
SQL Injection is a type of database attack technique where malicious SQL statements are inserted into an entry field of the database in a way that once it is executed, the database is exposed to an attacker for the attack. This technique is usually used for attacking data-driven applications to have access to sensitive data and perform administrative tasks on databases.
96. What is CHECK Constraint?
A CHECK constraint is used to limit the values or type of data that can be stored in a column. They are used to enforce domain integrity.
- Difference between TRUNCATE, DELETE, and DROP commands?
- DELETE removes some or all rows from a table based on the condition. It can be rolled back.
- TRUNCATE removes ALL rows from a table by de-allocating the memory pages. The operation cannot be rolled back
- DROP command removes a table from the database completely.
- What is a composite primary key?
The primary key created on more than one column is called a composite primary key.
- What do you mean by query optimization?
Query optimization is a process in which a database system compares different query strategies and selects the query with the least cost.
- What is schema?
A schema is a collection of database objects of a User.
- TOP 100+ Linux Interview Questions And Answers
- Python Interview Question And Answers
- HTML Interview Questions And Answers
- C# interview questions and answers
- DOTNET Interview Questions And Answers
- TOP 200+ JAVA Interview Questions And Answers
- [UPDATED] ASP.net Interview Questions And Answers
- C# Interview Questions And Answers
- C programming Interview Questions and Answers
- CPP Interview Questions And Answers
- JUNIT Interview Questions And Answers
- Networking Interview Questions And Answers
- LATEST Data Structure Interview Questions And Answers
- Android Interview Questions And Answers
- Operating System Interview Questions and Answers
For more Interview Questions And Answers click here