Top 100 SQL Interview Q&A*

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

What is an IDENTITY column in INSERT statements?

IDENTITY column is used in table columns to make that column an "auto-incrementing number" or a surrogate key.

What is the maximum size of a row?

8060 bytes

How will I retrieve all records of EMPLOYEES1 that are not present in EMPLOYEES2?

(SELECT * FROM EMPLOYEES1) - (SELECT * FROM EMPLOYEES2);

What is a Composite Key?

A Composite Key is a type of candidate key, which represents a set of columns whose values uniquely identify every row in a table. Example: If EmployeeID and EmployeeName in table EMP is combined to uniquely identify a row, it is called a Composite Key.

What is a Composite Primary Key?

A Composite Primary Key is a set of columns whose values unique identify every row in a table. What it means is that, tables which contain primary key will be indexed based on columns specified in the primary key. This key will be referred in Foreign Key tables. Example: If combined effect of columns EmployeeID and EmployeeName in a table is required to uniquely identify a row, it is called a Composite Primary Key. In this case, both the columns will be represented as a Primary Key.

What is a Data Warehouse?

A Data Warehouse is a central repository of data from multiple sources of information. Those data are consolidated, transformed, and made available for mining and online processing. Note, subsets of Data Warehouses are often called Data Marts.

What is DBMS?

A Database Management System (DBMS) is a program that controls creation, maintenance and use of a database. DBMS can be termed as File Manager that manages data in a database rather than saving it in file systems.

What is a Database Query?

A Database Query is a piece of code written in order to retrieve specific information from the database. A query can be designed in such a way that it matches our expectation of the result sets. Simply put, it is a question posed to the database.

What is a Database Relationship?

A Database Relationship is defined as the connection between the tables in a database. These are various data basing relationships, and they are as follows: (1) 1-to-1 Relationship (2) 1-to-Many Relationship (3) Many-to-Many Relationship (4) Self-Referencing Relationship

What is a Trigger?*

A Database Trigger is a piece of code or programs that automatically executes with response to some event on a table or view in a database. Mainly, trigger helps to maintain the integrity of the database. Example: When a new student is added to the student database, new records should be created in the related tables like Exam, Score, and Attendance tables.

What is a Foreign Key?

A Foreign Key is a field in one table which can be related to the primary key of another table. Relationship needs to be created between two tables by referencing foreign key with the primary key of another table. In simpler words, the foreign key is defined in a second table, but it refers to the primary key in the first table.

What is a Primary Key?

A Primary Key is a combination of fields which uniquely specify a row. This is a special kind of unique key, and it has implicit NOT NULL constraint. This means that Primary Key values cannot be NULL.

What is a Subquery? What are the types of Subqueries?

A Subquery is a query nested within another query. The outer query is the called the main query, and the inner quest is called the subquery. Subqueries are always executed first, and the result of the subquery is passed onto the main query. There are 2 types of subqueries: (1) Correlated Subqueries: these cannot be considered as independent queries, but can refer to columns in a table listed after FROM clause of the main query. (2) Non-Correlated Subqueries: these can be considered as independent queries and the outputs of these subqueries are substituted in the main queries.

What is a Unique Key?

A Unique Key constraint uniquely identifies each record in the database. This provides uniqueness for the column or set of columns. A Primary Key constraint has automatic unique constraint defined on it. But not, in the case of Unique Key. There can be multiple unique constraints defined per table, but only one Primary Key constraint defined per table.

What are the different index configurations a table can have?

A table can have one of the following index configurations: > No indices > A clustered index > A clustered index and many non-clustered indices > A non-clustered index > Many non-clustered indices

What is a Table? What are Fields and Records?

A table is a set of data that is organized in a model with Columns and Rows. Columns can be categorized as vertical, and Rows as horizontal. Fields are table columns, while Records are table rows. A table has specified number of columns called Fields but can have any number of rows which are called Records.

What is an ALIAS command? (Hint: AS)

ALIAS name can be given to a table or column. This alias name can be referred in WHERE clause to identify the table or column. Note that adding AS command between column name and aliases are optional, but highly recommended for better readability. Example: SELECT ST.StudentID, EX.Result from Student ST, Exam as EX WHERE ST.StudentID = EX.StudentID

What is AUTO INCREMENT?

AUTO INCREMENT command allows the user to create a unique number to generated when a new record is inserted into the table. Note that AUTO INCREMENT can be used in Oracle and IDENTITY can be used in SQL Server. Generally this command can be used whenever PRIMARY KEY is used.

What are the Advantages and Disadvantages of Views in a DB?

Advantages: (1) Views don't store data in a physical location (2) Views can be used to hide some of the columns from the table (3) Views can provide Access Restriction, since data insertion, alteration, and deletion is not possible on the view Disadvantages: (1) When a table is dropped, associated views become irrelevant. (2) Since views are created when a query requesting data from the views are triggered, its a bit slow (3) When views are created for large tables, it occupies much more memory.

What are aggregate and scalar functions?

Aggregate functions are used to evaluate mathematical calculations and return single values. This an be calculated from the columns in a table. Example: COUNT(), AVG(), SUM(), MIN(), MAX() - Calculated with respect to numeric values Scalar functions return a single value based on the input value. EXAMPLE: UCASE(), LCASE(), NOW() - Calculated with respect to strings

What is an Index? What are all the different types of Indices?*

An index is a performance tuning method of allowing faster retrieval of records from the table. An index creates an entry for each value and it will be faster to retrieve data. This indexing does not allow the field to have duplicate values if the column is uniquely indexed. Unique index can be applied automatically when primary key is defined. (1) Clustered Index: This type of index reorders the physical order of the table and search based on the key values. Each table can have only one clustered index. (2) Non-Clustered Index: This type of index does not alter the physical order of the table and maintains logical order of data. Each table can have 999 non-clustered indexes.

What is an Outer Join?*

An outer join includes rows from tables when there are no matching values in the tables.

What is Denormalization?*

Denormalization is a technique used to access the data from higher to lower normal forms of database. It is also the process of introducing redundancy into a table by incorporating data from the related tables.

Which TCP/IP port does SQL Server run on? How can it be changed?

By default, SQL Server runs on port 1433. It can be changed from the Network Utility TCP/IP properties.

What is Collation?*

Collation is defined as a set of rules that determine how character data can be stored and compared. This can be used to compare English characters 'A' and, other language characters and also depends on the width of the characters. ASCII values can be used to compare these character data.

What is a Constraint?

Constraints can be used to specify the limit on the data type of the table columns. Constraints can be specified while creating or altering the table statement. Sample constraints include: > NOT NULL > CHECK > DEFAULT > UNIQUE > PRIMARY KEY > FOREIGN KEY

What is Cross Join?

Cross Join will return all the records where each row from the first table is combined with each row from the second table.

What is Data Integrity?

Data Integrity defines the accuracy and consistency of data stored in the database. It can also define integrity constraints to enforce business rules on the data when it is entered into the application or database.

What is a Database Lock? What are the types of locks?

Database Lock tells a transaction, if the data item in question is currently being used by other transactions. (1) Shared Lock: When a shared lock is applied on a data item, other transactions can only read the item, but can't write into it. (2) Exclusive Lock: When an exclusive lock is applied on a data item, other transactions can't read or write into it.

What is a Database?

Database is nothing but an organized form of data for easy access, storing, retrieval and managing of data. This is also known as structured form of data which can be accessed in many ways.

What is a Database Transaction?

Database transactions take databases from one consistent state to another. At the end of the transaction, the system must be in the prior state if transaction fails, or the status of the system should reflect the successful completion if the transaction goes through.

What are the different types of Collation Sensitivity?

Following are the different types of Collation Sensitivity: > Case Sensitivity (A vs a or B vs b) > Accent Sensitivity > Kana Sensitivity (Japanese Kana characters) > Width Sensitivity (Single byte character vs double byte character)

What is a Materialized View?

Materialized Views are also views but are disk-based. Materialized Views get updated on specific duration, based upon the interval specified in the query definition. We can index Materialized Views.

What is Normalization?*

Normalization is the process of minimizing redundancy and dependency by organizing fields and tables of a database. The purpose of normalization is to add, delete, or modify fields that can be made in a single table.

What is Online Transaction Processing (OLTP)?

Online Transaction Processing (OLTP) manages transaction-based applications which can be used for data entry and easy retrieval processing of data. This processing makes life easier in terms of simplicity and efficiency. It produces faster, more accurate results and expenses with respect to OTLP. Example: Bank Transactions on a daily basis.

What are the properties and different types of Sub-Queries?

Properties of Sub-Queries: > A sub-query must be inclosed in parentheses. > A sub-query must be put in the RHS of the comparison operator > A sub-query cannot contain an ORDER BY clause > A query can contain more than one sub-query Types of Sub-Queries: > Single-row sub-query, where the sub-query returns only one row > Multiple-row sub-query, where the sub-query returns multiple rows > Multiple-column sub-query, where the sub-query returns multiple columns

What are properties of a Transaction? (Hint: LSD)

Properties of the transaction can be summarized as ACID Properties. 1. Atomicity: A transaction consists of many steps. When all the steps in a transaction get completed, it will get reflected in DB or if any step fails, all transactions are rolled back 2. Consistency: The DB will move from one consistent state to another, if the transaction succeeds and remain in the original state, if the transaction fails. 3. Isolation: Every transaction should operate as if it is the only transaction in the system. 4. Durability: Once a transaction has completed successfully, the updated rows/records must be available for all other transactions on a permanent basis.

What is RDBMS?

RDBMS stands for Relational Database Management System. RDBMS store the data into the collection of tables which is related by common fields between the columns of the table. It also provides relational operators to manipulate the data stored into the tables

What are the differences among ROWNUM, RANK, and DENSE_RANK?

ROW_NUMBER assigns contiguous, unique numbers from 1...N to a result set. RANK does not assign unique numbers, nor does it assign contiguous numbers. If two records tie for second place, no record will be assigned the 3rd rank as no one came in 3rd, according to RANK. DENSE_RANK, like RANK, also does not assign unique numbers, but it does assign contiguous numbers. Even though 2 records tied for 2nd place, there is a 3rd place record. NOTE: contiguous means adjacent, neighboring. i.e. This is contiguous => 1, 2, 3, 4; This is not => 1, 2, 4, 7.

How to create recursive query in SQL Server?

Recursive queries can be created in SQL using "stored procedure", but you can also use CTE (Common Table Expression). It might be also worth asking about performance AS CTE is not always very fast.

Write 3 different queries to get an accurate count of the number of records in a table.

SELECT * FROM Table1; SELECT COUNT(*) FROM Table1; SELECT rows FROM sysindexes WHERE id = OBJECT_ID(Table1) and indid < 2;

How can you create an empty table from an existing table?

SELECT * INTO StudentCopy FROM Student WHERE 1 = 2; Here, we are copying student table to another table with the same structure but no rows copied over.

How do you select unique records from a table?

SELECT DISTINCT StudentID, StudentName FROM Student; Select unique records from a table using DISTINCT keyword.

Which command using Query Analyzer will give you the version of SQL Server and the OS?

SELECT SERVERPROPERTY ('productversion'), SERVERPROPERTY ('productlevel') AND SERVERPROPERTY ('edition');

How do you fetch common records from two tables?

SELECT StudentID FROM Student INTERSECT SELECT StudentID FROM Exam;

Define SQL's INSERT Statement.

SQL INSERT is used to add rows to a table. For a full row insert, SQL query should start with "INSERT INTO" statement followed by table name and VALUE command, followed by the specific values that need to be inserted into a table. INSERT can be used to either insert a single complete row or a single partial row.

What is SQL Injection?

SQL Injection is one of the techniques used by hackers to hack a website by injecting SQL commands into data fields.

What are wild cards used in database for Pattern Matching?

SQL LIKE operator is used for pattern matching. Note that this operation generally takes longer to process so before using it, consider the suggestions given below on when and where to used wild card search. (1) Don't overuse wild cards. If another search operator will do, use it instead. (2) When you do use wild cards, try not to use them at the beginning of the search pattern, unless absolutely necessary. Search patterns that begin with wild cards are the slowest to process. (3) Pay careful attention to the placement of wild card symbols. If they are misplaced, you might not return the data you intended.

What is SQL Server Agent?

SQL Server Agent plays an important role in the day-to-day tasks of a database administrator (DBA). Its purpose is to ease the implementation of tasks for the DBA, with its full-function scheduling engine, which allows you to schedule your own jobs and scripts.

What is the difference among UNION, MINUS, and INTERSECT?

SQL UNION combines the results from 2 tables and eliminates duplicate records from the result set. SQL MINUS (-) operator when used between 2 tables, gives us all the rows from the first table except the rows which are present in the second table. SQL INTERSECT operator returns us only the matching or common rows between 2 result sets.

Define SQL's UPDATE Statement.

SQL UPDATE is used to update data in a row or set of rows specified in the filter condition. The basic format of an SQL UPDATE statement is UPDATE followed by table name to be updated and SET command, followed by column names and their new values followed by filter condition that determines which rows should be updated.

What is SQL?

SQL stands for Structured Query Language, and it is used to communicate with the Database. This is a standard language used to perform tasks such as retrieval, alteration, insertion, and deletion of data from a database.

What is Self Join? Why is it useful?

Self Join is the act of joining one table with itself. It is only useful to convert a hierarchical structure into a flat structure.

What are the Advantages and Disadvantages of Stored Procedure?*

Stored procedure can be used as modular programming - means create once, store, and call for several times whenever required. The advantages are that this supports faster execution instead of executing multiple queries. Moreover, this reduces network traffic and provides better security to the data. The disadvantages is that it can only be executed in the database and utilizes more memory in the database server.

What is the difference between DELETE, TRUNCATE, and DROP commands?*

The DELETE command is used to remove records from a table, and WHERE clause can be used for conditional set of parameters. Commit and Rollback can be performed after this operation. The TRUNCATE command removes all records from the table. This operation cannot be rolled back. The DROP command is used to drop tables, keys (i.e. PK, FK), or databases.

What is the difference between JOIN and UNION?

The JOIN operation allows us to "lookup" records in another table based on the given conditions between two tables. Example: If we have department ID of each employee, then we can use this department ID of Employee table to join with the department ID of Department table to lookup department names. The UNION operation allows us to add 2 similar datasets to create a resulting dataset that contains all of the data from the source datasets. UNION does not require any condition for joining. SELECT deptID FROM EMP JOIN DEPT ON EMP.deptID = DEPT.id; Example: If you have 2 Employee tables with the same structure, you can UNION them to create one result set that will contain all the employees from both tables. SELECT * FROM EMP1 UNION SELECT * FROM EMP2;

What are all the different Normalizations?

The normal forms can be divided into 4 forms: (1) First Normal Form (1NF): This should remove all the duplicate columns from the table. Creation of tables from the related data and identification of unique columns. (2) Second Normal Form ( 2NF): Meeting all requirements of the first normal form. Placing the subsets of data in separate tables and Creation of relationships between the tables using primary keys. (3) Third Normal Form (3NF): This should meet all requirements of 2NF. Removing the columns which are not dependent on primary key constraints. (4) Fourth Normal Form (4NF): Meeting all the requirements of the third normal form and it should not have multi-value dependencies.

How can we transpose a table using SQL (switching rows and columns or vice-versa)?*

The usual way to do it in SQL is to use CASE statement or DECODE statement.

What are all the types of User Defined Functions?

There are 3 types of User Defined Functions: (1) Scalar Functions (2) Inline Table Valued Functions (3) Multi-Statement Valued Functions

What are the types of Triggers?*

There are 4 main types of triggers: (1) INSERT (2) DELETE (3) UPDATE (4) INSTEAD OF

What are the types of Joins? Explain each.*

There are various types of joins which can be used to retrieve data and it depends on the relationship between tables. (1) Inner Join: returns records when there is at least one match of rows between the tables (2) Right Join: returns records which are common between tables and all rows of Right-Hand-Side (RHS) table. Simply put, it returns all the records from the RHS table even though there are no matches in the LHS table. (3) Left Join: returns records which are common between tables and all the rows of Left-Hand-Side (LHS) table. Simply put, it returns all the records from the LHS table even though there are no matches in the RHS table. (4) Full Join: returns records when there are matching rows in any one of the tables. This means, it returns all the records from the LHS and RHS tables. (5) Self Join: returns records of the original table itself. It is only useful to convert a hierarchical structure into a flat structure.

How would apply a date range filter?

There is no single way to perform this. But here are a few methods: (1) You can use a simple condition using >= or <= or similarly use BETWEEN/AND but the trick is to know your exact data type. (2) Sometimes date fields contain time and that is where the query can go wrong so it is recommended to use some date related functions to remove the time issue. In SQL Server common functions to do that is DATEDIFF function. (3) You also have to be aware of different time zones and server time zones. (4) To increase query performance you may still want to use BETWEEN however you should be aware of proper format you need to use, else it might misbehave during filtering.

What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?*

They both specify a search condition for a group or an aggregate. But the difference is that HAVING can only be used with the SELECT statement. HAVING is typically used in GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause. HAVING is basically used with the GROUP BY function in a query whereas WHERE is applied to each record before they are part of the GROUP BY function in a query.

When do you use UPDATE_STATISTICS command?

This command is used when a large processing of data has occurred. If any large amounts of deletions, any modifications, or Bulk Copy into the tables has occurred, it has to update the indexes to take these changes into account. UPDATE_STATISTICS updates the indices on these tables accordingly.

What are User Defined Functions?

User Defined Functions are the functions written to use specific functionality/logic whenever required. Generally, whenever you are writing the same logic several times, it can be encapsulated into a function that can be called multiple times instead.

What is a View?

Views are virtual tables. Unlike tables that contain data, views simply contain queries that dynamically retrieve data when used.


Kaugnay na mga set ng pag-aaral

CompTIA(220 - 1001) - Networking (Test Prep)

View Set

WEEK 2 [BSN 340] "FEEDING, EATING AND PERSONALITY DISORDERS"

View Set

Ch 9 Obversion, Conversion, and Contraposition

View Set

ATI Health Assess 2.0: Rectum and Genitourinary

View Set

Econ Final Study Guide Chapter 2

View Set

Ch 44 Drugs Acting on the Renin-Angiotensin-Aldosterone System

View Set

AP Biology Chapter 17 Study Guide

View Set