SQL Interview

Ace your homework & exams now with Quizwiz!

Inner Join

(a.k.a. "simple join"): Returns all rows for which there is at least one match in BOTH tables. This is the default type of join if no specific JOIN type is specified.

What are the 3 different subsets of SQL?

1. DDL (Data Definition Language): It allows you to perform various operations on the database such as CREATE, ALTER and DELETE objects. 2. 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. 3. DCL ( Data Control Language) - It allows you to control access to the database. Example - Grant, Revoke access permissions.

What are the two types of DBMS?

1. Relational Database Management System: The data is stored in relations (tables). Example - MySQL. 2. Non-Relational Database Management System: There is no concept of relations, tuples and attributes. Example - Mongo

Cross Join

: Returns all records where each row from the first table is combined with each row from the second table (i.e., returns the Cartesian product of the sets of rows from the joined tables). Note that a CROSS JOIN can either be specified using the CROSS JOIN syntax ("explicit join notation") or (b) listing the tables in the FROM clause separated by commas without using a WHERE clause to supply join criteria ("implicit join notation").

What is DBMS

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.

Are NULL values 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 which is unavailable, unknown, assigned or not applicable whereas a zero is a number and blank space is a character.

What is a Primary key?

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

What is a Stored Procedure?

A Stored Procedure is a function which consists of many SQL statements to access the database system. Several SQL statements are consolidated into a stored procedure and execute them whenever and wherever required which saves time and avoid writing code again and again.

What is Cursor?

A cursor is a database object which is used to manipulate data in a row-to-row manner. Cursor follows steps as given below Declare Cursor Open Cursor Retrieve row from the Cursor Process the row Close Cursor Deallocate Cursor

What is a database?

A database is a structured collection of data.

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 =.

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: Table: StudentInformation Field: Stu Id, Stu Name, Stu Marks

What are transaction and its controls?

A transaction can be defined as the sequence task that is performed on databases in a logical manner to gain certain results. Operations performed like Creating, updating, deleting records in the database comes from transactions. In simple word, we can say that a transaction means a group of SQL queries executed on database records. There 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 such as all changes made by the transaction are reverted back and database remains as before SET TRANSACTION: Set the name of transaction SAVEPOINT: It is used to set the point from where the transaction is to be rolled back

What is a transaction?

A transaction is a sequence of code that runs against a database. It takes the database from one consistent state to another.

What is a view?

A view is a virtual table which consists of a subset of data contained in a table. Since views are not present, it takes less space to store. View can have data of one or more tables combined and it depends on the relationship.

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.

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.

What is an ALIAS command?

ALIAS name can be given to any table or a column. This alias name can be referred in WHERE clause to identify a particular table or a column.

What are the advantages of Views?

Advantages of Views: Views restrict access to the data because the view can display selective columns from the table. Views can be used to make simple queries to retrieve the results of complicated queries. For example, views can be used to query information from multiple tables without the user knowing

What are aggregate and scalar functions?

Aggregate functions are used to evaluate mathematical calculation and returns 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 string.

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.

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.

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.

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.

What is the difference between clustered and non clustered index in SQL?

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.

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.

What is Collation?

Collation is set of rules that check how the data is sorted by comparing it. Such as Character data is stored using correct character sequence along with case sensitivity, type, and accent.

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

Why do we use SQL constraints?

Constraints are used to set the rules for all records in the table. If any constraints get violated then it can abort the action that caused it. Constraints are defined while creating the database itself with CREATE TABLE statement or even after the table is created once with ALTER TABLE statement.

What are Constraints?

Constraints are used to specify the limit on the data type of the table. It can be specified while creating or altering the table statement. The sample of constraints are: NOT NULL CHECK DEFAULT UNIQUE PRIMARY KEY FOREIGN KEY

What is the difference between DROP and TRUNCATE commands?

DROP command removes a table and it cannot be rolled back from the database whereas TRUNCATE command removes all the rows from the table.

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.

What is Database Black Box Testing?

Database Black Box Testing involves Data Mapping Data stored and retrieved Use of Black Box techniques such as Equivalence Partitioning and Boundary Value Analysis (BVA)

What is Database White Box Testing?

Database White Box Testing involves Database Consistency and ACID properties Database triggers and logical views Decision Coverage, Condition Coverage, and Statement Coverage Database Tables, Data Model, and Database Schema Referential integrity rules

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 the mining as well as online processing. Warehouse data also have a subset of data called Data Marts.

What do you mean by Denormalization?

Denormalization refers to a technique which is used to access data from higher to lower forms of a database. It helps the database managers to increase the performance of the entire infrastructure as it introduces redundancy into a table. It adds the redundant data into a table by incorporating database queries that combine data from various tables into a single table.

What are Entities and

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.

Full Join

FULL JOIN (or FULL OUTER JOIN): Returns all rows for which there is a match in EITHER of the tables. Conceptually, a FULL JOIN combines the effect of applying both a LEFT JOIN and a RIGHT JOIN; i.e., its result set is equivalent to performing a UNION of the results of left and right outer queries.

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.

What is a Foreign key?

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.

Full Join:

Full join returns all the records when there is a match in any of the tables. Therefore, it returns all the rows from the left-hand side table and all the rows from the right-hand side table.

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.

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.

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.

State 3 properties of Relational databases?

In relational databases, each column should have a unique name Sequence of rows and columns in relational databases are insignificant All values are atomic and each row is unique

Inner join:

It is used to return all the rows from multiple tables where the join condition is satisfied.

Left Join

LEFT JOIN (or LEFT OUTER JOIN): Returns all rows from the left table, and the matched rows from the right table; i.e., the results will contain all records from the left table, even if the JOIN condition doesn't find any matching records in the right table. This means that if the ON clause doesn't match any records in the right table, the JOIN will still return a row in the result for that record in the left table, but with NULL in each column from the right table.

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_'

Left Join:

Left Join in MySQL is used to return all the rows from the left table but only the matching rows from the right table where the join condition is fulfilled.

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

What is the use of NVL function?

NVL function is used to convert the null value to its actual value.

What is Normalization? How many Normalization forms are there?

Normalization is used to organize the data in such manner that data redundancy will never occur in the database and avoid insert, update and delete anomalies. There are 5 forms of Normalization First Normal Form (1NF): It removes all duplicate columns from the table. Creates table for related data and identifies unique column values First Normal Form (2NF): Follows 1NF and creates and places data subsets in an individual table and defines relationship between tables using primary key Third Normal Form (3NF): Follows 2NF and removes those columns which are not related through primary key Fourth Normal Form (4NF): Follows 3NF and do not define multi-valued dependencies. 4NF also known as BCNF

What is the difference between clustered and non-clustered indexes?

One table can have only one clustered index but multiple nonclustered indexes. Clustered indexes can be read rapidly rather than non-clustered indexes. Clustered indexes store data physically in the table or view and non-clustered indexes do not store data in table as it has separate structure from data row

What is the difference between primary key and unique constraints?

Primary key cannot have NULL value, the unique constraints can have NULL values. There is only one primary key in a table, but there can be multiple unique constrains. The primary key creates the cluster index automatically but the Unique key does not.

What is a composite primary key?

Primary key created on more than one column is called composite primary key.

What are properties of the transaction?

Properties of transaction are known as ACID properties, such as Atomicity: Ensures the completeness of all transactions performed. Checks whether every transaction is completed successfully if not then transaction is aborted at the failure point and the previous transaction is rolled back to its initial state as changes undone Consistency: Ensures that all changes made through successful transaction are reflected properly on database Isolation: Ensures that all transactions are performed independently and changes made by one transaction are not reflected on other Durability: Ensures that the changes made in database with committed transactions persist as it is even after system failure

Right Join

RIGHT JOIN (or RIGHT OUTER JOIN): Returns all rows from the right table, and the matched rows from the left table. This is the exact opposite of a LEFT JOIN; i.e., the results will contain all records from the right table, even if the JOIN condition doesn't find any matching records in the left table. This means that if the ON clause doesn't match any records in the left table, the JOIN will still return a row in the result for that record in the right table, but with NULL in each column from the left table.

What do you mean by recursive stored procedure?

Recursive stored procedure refers to a stored procedure which calls by itself until it reaches some boundary condition. This recursive function or procedure helps the programmers to use the same set of code n number of times.

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 Realtionship

What are 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).

Right Join:

Right Join in MySQL is used to return all the rows from the right table but only the matching rows from the left table where the join condition is fulfilled.

How to write a query to show the details of a student from Students table whose name starts with K?

SELECT * FROM Student WHERE Student_Name like '%K';

Write a SQL query to find the names of employees that begin with 'A'?

SELECT * FROM Table_name WHERE EmpName like 'A%'

List the ways to get the count of records in a table?

SELECT * FROM table1 SELECT COUNT(*) FROM table1 SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid < 2

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 object like SELECT, INSERT, UPDATE, DELETE, ALL etc.

What is SQL Injection?

SQL Injection is a type of database attack technique where malicious SQL statements are inserted into an entry field of database such that once it is executed the database is opened for an attacker. This technique is usually used for attacking Data-Driven Applications to have an access to sensitive data and perform administrative tasks on databases. For Example: SELECT column_name(s) FROM table_name WHERE condition;

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.

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

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.

What is the difference between SQL and MySQL?

SQL is a standard language which stands for Structured Query Language based on the English language whereas MySQL is a database management system. SQL is the core of relational database which is used for accessing and managing database, MySQL is an RDMS (Relational Database Management System) such as SQL Server, Informix etc.

What are STUFF and REPLACE function?

STUFF Function: This function is used to overwrite existing character or inserts a string into another string. Syntax: STUFF(string_expression,start, length, replacement_characters) REPLACE function: This function is used to replace the existing characters of all the occurrences. Syntax: REPLACE (string_expression, search_string, replacement_string)

What are Scalar Functions in SQL?

Scalar Functions are used to return a single value based on the input values. Scalar Functions are as follows UCASE(): Converts the specified field in upper case LCASE(): Converts the specified field in lower case MID(): Extracts and returns character from text field FORMAT(): Specifies the display format LEN(): Specifies the length of text field ROUND(): Rounds up the decimal field value to a number

How can you fetch first 5 characters of the string?

Select SUBSTRING(StudentName,1,5) as studentname from student

What are the different set operators available in SQL?

Some of the available set operators are - Union, Intersect or Minus operators.

What is the difference between Nested Subquery and Correlated Subquery?

Subquery within another subquery is called as Nested Subquery. If the output of a subquery is depending on column values of the parent query table then the query is called Correlated Subquery. SELECT adminid(SELEC Firstname+' '+Lastname FROM Employee WHERE empid=emp. adminid)AS EmpAdminId FROM Employee This query gets details of an employee from Employee table.

What is the difference between DROP and TRUNCATE?

TRUNCATE removes all rows from the table which cannot be retrieved back, DROP removes the entire table from the database and it cannot be retrieved back.

What is the difference between DELETE and TRUNCATE?

The basic difference in both is DELETE is DML command and TRUNCATE is DDL DELETE is used to delete a specific row from the table whereas TRUNCATE is used to remove all rows from the table We can use DELETE with WHERE clause but cannot use TRUNCATE with it

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.

How many row comparison operators are used while working with a subquery?

There are 3-row comparison operators which are used in subqueries such as IN, ANY and ALL.

How many Aggregate Functions are available there in SQL?

There are 7 aggregate functions we use in SQL AVG(): Returns the average value from specified columns COUNT(): Returns number of table rows MAX(): Returns 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 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.

What are the different operators available in SQL?

There are three operators available in SQL, namely: Arithmetic Operators Logical Operators Comparison Operators

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.

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.

What are Local and Global variables?

These variables can be used or exist only inside the function. These variables are not used or referred by any other function. Global variables: These variables are the variables which can be accessed throughout the program. Global variables cannot be created whenever that function is called.

select case when null = null then 'Yup' else 'Nope' end as Result;

This query will actually yield "Nope", seeming to imply that null is not equal to itself! The reason for this is that the proper way to compare a value to null in SQL is with the is operator, not with =. Accordingly, the correct version of the above query that yields the expected result (i.e., "Yup") would be as follows: select case when null is null then 'Yup' else 'Nope' end as Result; This is because null represents an unknown value. If you don't know the value, you can't know whether it equals another value, so = null is always assumed to be false.

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.

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.

What does UNION do? What is the difference between UNION and UNION ALL?

UNION merges the contents of two structurally-compatible tables into a single combined table. The difference between UNION and UNION ALL is that UNION will omit duplicate records whereas UNION ALL will include duplicate records. It is important to note that the performance of UNION ALL will typically be better than UNION, since UNION requires the server to do the additional work of removing any duplicates. So, in cases where is is certain that there will not be any duplicates, or where having duplicates is not a problem, use of UNION ALL would be recommended for performance reasons.

What are three types of index?

Unique Index: 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. Clustered Index: 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: 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.

What is a Unique key?

Uniquely identifies a single row in the table. Multiple values allowed per table. Null values allowed.

What are the different authentication modes in SQL Server? How can it be changed?

Windows mode and Mixed Mode - SQL and Windows. You can go to the below steps to change authentication mode in SQL Server: Click Start> Programs> Microsoft SQL Server and click SQL Enterprise Manager to run SQL Enterprise Manager from the Microsoft SQL Server program group. Then select the server from the Tools menu. Select SQL Server Configuration Properties, and choose the Security page.

How can you fetch alternate records from a table?

You can fetch alternate records i.e both odd and even row numbers. For example- To display even numbers, use the following command: Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=0 Now, to display odd numbers: Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=1

How can you fetch common records from two tables?

You can fetch common records from two tables using INTERSECT.

How can you select unique records from a table?

You can select unique records from a table by using the DISTINCT keyword.

What do we need to check in Database Testing?

enerally, in Database Testing following thing is need to be tested Database Connectivity Constraint Check Required Application Field and its size Data Retrieval and Processing With DML operations Stored Procedures Functional flow


Related study sets

Combo with "Peds Exam 3a" and 2 others

View Set

Final Exam Review for Insur. Coding over Ch 7,8,10,11 and 12

View Set

Ch. 3.A - Legal Issues: Estate and Interest

View Set

Chapter 65: Caring for Clients with Skin, Hair, and Nail Disorders

View Set

Paulo Freire -- Pedagogy of the Oppressed

View Set

ASVAB Word Knowledge Set 6 - 30 words

View Set

AP Computer Science Principles Mid Term Review

View Set

BUL 3310 Exam 2, BUL3310 FSU Exam 2 Bailey

View Set