DBA adminstrator interview questions
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 with a single field as unique */ CREATE TABLE Students (ID INT NOT NULL UNIQUE Name VARCHAR(255) ); /* Create table with multiple fields as unique */ CREATE TABLE Students ( ID INT NOT NULL LastName VARCHAR(255) FirstName VARCHAR(255) NOT NULL CONSTRAINT PK_Student UNIQUE (ID, FirstName) ); /* Set a column as unique */ ALTER TABLE Students ADD UNIQUE (ID); /* Set multiple columns as unique */ ALTER TABLE Students ADD CONSTRAINT PK_Student /* Naming a unique constraint */ UNIQUE (ID, FirstName);
What is a query?
A command to retrieve data from tables /* select query */ SELECT fname, lname FROM myDb.students WHERE student_id = 1; /* action query */ UPDATE myDB.students SET fname = 'Captain', lname = 'America' WHERE student_id = 1;
What is a cross join?
A cross join does not have a WHERE or ON clause, therefore it produces the Cartesian product of the tables involved in the join. The size of a Cartesian product result set is the number of rows in the first table multiplied by the number of rows in the second table. SELECT stu.name, sub.subject FROM students AS stu CROSS JOIN subjects AS sub;
What is a cursor?
A cursor is a database object used by applications to manipulate data in a set on a row-by-row basis, instead of the typical SQL commands that operate on all the rows in the set at one time. In order to work with a cursor, we need to perform some steps in the following order: 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 OPEN statement 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 CLOSE statement to deactivate the cursor. Finally use the DEALLOCATE statement to delete the cursor definition and release the associated resources. /* Declare All Required Variables */ DECLARE @name VARCHAR(50) /* Declare Cursor Name*/ DECLARE db_cursor CURSOR FOR SELECT name FROM myDB.students WHERE parent_name IN ('Sara', 'Ansh') /* Open cursor and Fetch data into @name */ OPEN db_cursor FETCH next FROM db_cursor INTO @name /* Close the cursor and deallocate the resources */ CLOSE db_cursor DEALLOCATE db_cursor
What is an Index? Explain its different types.
A database index is a data structure that provides 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 */ CREATE INDEX index_name ON table_name (column_1, column_2); /* Drop Index */ DROP INDEX index_name; 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 myIndex ON 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.
What is a Primary Key?
A field (or group of fields) that uniquely identifies a given entity in a table /* Create table with a single field as primary key */ CREATE TABLE Students ( ID INT NOT NULL Name VARCHAR(255) PRIMARY KEY (ID) ); /* Create table with multiple fields as primary key */ CREATE TABLE Students ( ID INT NOT NULL LastName VARCHAR(255) FirstName VARCHAR(255) NOT NULL, CONSTRAINT PK_Student PRIMARY KEY (ID, FirstName) ); /* Set a column as primary key */ ALTER TABLE Students ADD PRIMARY KEY (ID); /* Set multiple columns as primary key */ ALTER TABLE Students ADD CONSTRAINT PK_Student /*Naming a Primary Key*/ PRIMARY KEY (ID, FirstName);
. What is a Foreign Key?
A primary key of one table that appears as an attribute in another table and acts to provide a logical relationship between the two tables /* Create table with foreign key - Way 1 */ CREATE TABLE Students ( ID INT NOT NULL Name VARCHAR(255) LibraryID INT PRIMARY KEY (ID) FOREIGN KEY (Library_ID) REFERENCES Library(LibraryID) ); /* Create table with foreign key - Way 2 */ CREATE TABLE Students ( ID INT NOT NULL PRIMARY KEY Name VARCHAR(255) LibraryID INT FOREIGN KEY (Library_ID) REFERENCES Library(LibraryID) ); /* Add a new foreign key */ ALTER TABLE Students ADD FOREIGN KEY (LibraryID) REFERENCES Library (LibraryID);
What is the SELECT statement?
A statement that retrieves data from the database. SELECT * FROM myDB.students;
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() BEGIN SELECT * FROM myDB.students; END $$ DELIMITER ;
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 ) BEGIN DECLARE 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 */ ELSE CALL calctotal(number+1); /* Recursive call */ SET total = total + score; /* Action after recursion */ END IF; END $$ /* End of procedure */ DELIMITER ;
What is a subquery?
A subquery is a SQL query nested inside a larger query. SELECT name, email, mob, address FROM myDb.contacts WHERE 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 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 subquery is substituted in the main query.
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.
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.
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.
What is an 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. /* Alias using AS keyword */ SELECT A.emp_name AS "Employee" B.emp_name AS "Supervisor" FROM employee A, employee B /* Alias without AS keyword */ WHERE A.emp_sup = B.emp_id;
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.
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: Case sensitivity: A and a are treated differently. Accent sensitivity: a and á are treated differently. Kana sensitivity: Japanese kana characters Hiragana and Katakana are treated differently. Width sensitivity: Same character represented in single-byte (half-width) and double-byte (full-width) are treated differently.
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.
What is normalization?
Converting poorly structured tables into two or more well-structured tables Each table should only have 1 "theme" OR Normalization represents the way of organizing structured data in the database efficiently. It includes 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.
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_copy FROM Students WHERE 1 = 2;
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
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.
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.
DBMS vs RDBMS
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.
What is RDBMS?
Relational Data Base Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. Relationships may be created and maintained across and among the data and tables. In a relational database, relationships between data items are expressed by means of tables. Interdependencies among these tables are expressed by data values rather than by pointers. This allows a high degree of data independence. An RDBMS has the capability to recombine the data items from different files, providing powerful tools for data usage. (Read more here)
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.
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. 1 Using the % wildcard to perform a simple searchThe % 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 students WHERE first_name LIKE 'K%' 2 Omitting the patterns using the NOT keywordUse 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 students WHERE first_name NOT LIKE 'K%' 3 Matching a pattern anywhere using the % wildcard twiceSearch for a student in the database where he/she has a K in his/her first name.SELECT * FROM students WHERE first_name LIKE '%Q%' 4 Using the _ wildcard to match pattern at a specific positionThe _ 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 students WHERE first_name LIKE '__K%' 5 Matching patterns for specific lengthThe _ 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 students WHERE first_name LIKE '___%' SELECT * /* Matches first names with exactly four characters */ FROM students WHERE first_name LIKE '____'
What is SQL?
SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
What is a self join?
Self-join is set to be query used to compare to itself. This is used to compare values in a column with other values in the same column in the same table. ALIAS ES can be used for the same table comparison. 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 B WHERE A.emp_sup = B.emp_id;
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: WHERE clause in SQL is used to filter records that are necessary, based on specific conditions. ORDER BY clause 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;
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;
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.
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 /* Fetch the union of queries */ SELECT name FROM Students UNION SELECT name FROM Contacts; /* Fetch the union of queries with duplicates*/ SELECT name FROM Students UNION ALL SELECT name FROM Contacts; /* Fetch names from students */ SELECT name FROM Students MINUS /* that aren't present in contacts */ SELECT name FROM Contacts; /* Fetch names from students */ SELECT name FROM Students INTERSECT /* that are present in contacts as well */ SELECT name FROM Contacts;
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.
What is a database?
an organized collection of data, stored and retrieved digitally from a remote or local computer system.
What is denormalization?
the process of transforming a logical data model into a physical model is efficient for the most-often-needed tasks OR Denormalization is the inverse process of normalization, where the normalized schema is converted into a schema which 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 query processor by an over-normalized structure. What are the various forms of Normalization? Q29 https://www.interviewbit.com/sql-interview-questions/
What is a DBMS?
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 softwares.
What are the TRUNCATE, DELETE and DROP statements?
DELETE statement is used to delete rows from a table. DELETE FROM Candidates WHERE 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 is deleted and the table structure is removed from the database. DROP TABLE Candidates;
What is Data Integrity?
Data being ACCURATE and CONSISTENT throughout its life.
What are Entities/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 employees table in a company's database can be associated with the salary table in the same database.
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.