Showing posts with label sql interview questions. Show all posts
Showing posts with label sql interview questions. Show all posts

Database Interview Practice Concepts

Database Interview Practice Concepts

There are many different types of databases nowadays, with the advent of alternative storage techniques (CouchDB, Amazon Simple Storage, Google’s BigTable, etc.) but the relational database is still the most popular. Virtually all relational databases use structured query language (SQL) to access the information within. We’ll focus on MySQL syntax for these database problems because it’s the most widely used relational database in industry, but others such as MSSQL, Oracle, SQLite or PostgreSQL all have similar syntax.

Relational Databases

A relational database stores information in a group of tables called a schema. Each table consists of rows and columns. Often, tables represent a class where the columns define the table’s properties and each row represents an object of that class. Each table must contain at least one column, but do not necessarily contain any rows. Every column is associated with a specific type as well as possible constraints, and a row must contain data for every column with matching types.

A key for a table is a column or possibly columns that contains a unique identification for a row in the table. A primary key is selected if multiple columns uniquely identify a row. Tables can be joined by foreign keys, which is usually a primary key from another table.

Just as a reminder, SQL is usually not case sensitive, but convention dictates capitalizing keywords entirely (e.g. SELECT) and camel casing the name of a table (e.g. TableName) whereas row names are all lowercase and often delimited by underscores (e.g. row_name).

Most interview questions involving databases consists of how to write queries for a specific database schema. For practice, we’ve provided a sample stock market related schema below:


Companies (
symbol INT(11) PRIMARY KEY NOT NULL,
name VARCHAR(128),
ceo VARCHAR(128),
employees INT(6),
)

Financials (
symbol INT(11) PRIMARY KEY NOT NULL,
revenue DECIMAL(8,2),
expenses DECIMAL(8,2),
FOREIGN KEY symbol REFERENCES Companies
)

Notice that the primary key is not an auto-incremented integer but instead the stock ticker. As a general design decision, integer auto-incrementing keys should only be used when there is no other possible unique identifier for the table.

To insert values into a table, use the INSERT statement, whose syntax is as follows:
INSERT INTO TABLE(row_names…) VALUES(row_values);
For instance, to insert a company called TimeSavers run by Missy Jones
and 63 other employees with a stock ticker of TS into the Companies
table, you would use the following query:
INSERT INTO Companies(symbol, name, ceo, employees)
    VALUES(‘TS’, ‘TimeSavers’, ‘Missy Jones’, 63);
To retrieve values from a table, use the SELECT statement; for the example above,
SELECT * FROM Companies;
will yield the following results assuming they were already stored in the database:
Symbol Name CEO Employees
AC Able’s Coffee Jason Able 129
OS OfficeSuppliers Sheryl Tera 35
GD Grocery Deluxe Mike Perez 88
TS TimeSavers Missy Jones 63
You can choose to only display certain fields. For example,
SELECT symbol, revenue FROM Financials; 
Symbol  Revenue  
AC $1,005,000.00
GD $800,000.00
OS $500,000.00
TS $250,000.00

Also, you have the ability to specify ranges of values you’re interested in:

SELECT symbol, revenue FROM Financials WHERE revenue > 1000000;
Symbol  Revenue
AC $1,005,000.00

The WHERE clause can include multiple ranges as well as use AND or OR statements to make further classifications possible. There are also GROUP BY and ORDER BY clauses to sort data, and aggregate clauses such as MIN, MAX, SUM, and AVG to perform relatively simple functions on sets of data.

To combine data from two different tables, a join is required.

SELECT symbol, name, revenue FROM Companies, Financials
WHERE Companies.symbol=Financials.symbol;
Symbol  Name   Revenue
AC Able’s Coffee $1,005,000.00
OS OfficeSuppliers $500,000.00
GD Grocery Deluxe $800,000.00
TS TimeSavers $250,000.00

SQL Injections

When writing SQL queries that include variables, it is imperative to understand SQL injection because it is a very real and dangerous threat to the security of your database. Unethical attackers may be able to gain access to information or wipe out your data by injecting their own query code. This can happen if you don’t escape certain special characters, most notably quotes.

For instance, if your query contains a variable $name whose value is obtained from a user input such as a web form, you must take care to escape special characters. Virtually every programming language has a function to do this; in PHP mysql_real_escape_string($str) accomplishes this. The reason behind escaping is to prevent attackers from ending your query prematurely and inserting their own queries afterwards.

Here is an example; assume your query is the following:

SELECT * FROM Companies WHERE name=’$name’;

An attacker may fill out the $name field as such:
Attacker’; DELETE FROM Companies WHERE 1=1; '--

This leads to the following combined query after variable substitution:
SELECT * FROM Companies WHERE name=’Attacker’; DELETE FROM Companies WHERE 1=1; '--’;

Because the attacker included an ending quote, he is able to insert his own query after yours, thereby deleting your entire table’s worth of data!

Granted, the attacker requires some knowledge about the database such as table names, but most organizations use common names that are relatively easy to guess. As such, it is always a good idea to escape your queries.

Transactions

A database transaction is a collection of commands grouped into an indivisible unit of work. Transactions basically model real world events that are atomic (meaning that they either happen, or they don’t) but require multiple database operations to achieve.

The classic example is for financial transactions such as ATM withdrawals. Although it seems like a withdrawal is a single operation, it actually requires several steps: checking the account balance, moving the money out of the account, and adding the money into the ATM’s cash log.

As a result, if a withdrawal is not treated as a transaction, unexpected side effects may occur. For example, a husband and wife have access to a joint bank account which has a balance of $100. The husband and wife simultaneously withdraw $100, but if there were no database transactions, their account would be at $0 instead of -$100 afterwards!

This is because as the husband issues the withdrawal, the ATM checks the account to see if there is enough money; since $100 >= $100, there is adequate funds. Simultaneously, the wife issues the withdrawal and the check also passes. Then the husband’s machine deducts $100 from the account ($100 - $100 = 0) and spits out the money, and the wife’s machine does the same thing ($100 - $100 = 0), so the final balance of their account is $0.

This is bad news for the bank. Transactions can remove this possibility by requiring that all three steps be performed in a row as one operation until another operation can take place.

A transaction must follow the ACID principles to ensure data integrity. ACID is an acronym that stands for the following properties:

Atomicity – if all steps in a transaction do not succeed, all changes are rolled back. Changes are only made if the entire transaction is successful.

Consistency – the state of the database must be correct and consistent at the beginning and end of the transaction.

Isolation – every step in a transaction is performed without other operations accessing the database. Only one transaction may be processed at a time.

Durability – transactional changes, once successful, remain persistent in the database and will survive system failure. This is usually achieved by storing all operations in a log for replay later if necessary.

If all of these principles are followed, the transactions will ensure data integrity. However, the checks for all of these principles are computationally intensive and require a significant amount of running time, so not all databases implement ACID properties in order to improve performance.

Assume the practice questions refer to the tables and data from the previous examples.

Practice Question: Insert a company called Maximal Fitness run by Max Levin and 72 other employees with a ticker symbol of MF into the Companies table.

INSERT INTO Companies(Symbol, Name, CEO, Employees)
VALUES(‘MF’, ‘Maximal Fitness’, ‘Max Levin’, 72);

Practice Question: Select the name of the companies that have revenues over $300,000 and under $1,000,000.

SELECT Companies.name FROM Companies, Financials
WHERE Financials.revenue > 300000 AND Financials.revenue < 1000000;

Practice Question: Select the average number of employees amongst all companies.

SELECT AVG(employees) FROM Companies;

SQL Interview questions

SQL Interview questions
Q.What is the use of the DROP option in the ALTER TABLE comm&?
It is used to drop constraints specified on the table.
Q. What is the value of ‘comm’ & ‘sal’ after executing the following query if the initial
value of ‘sal’ is 10000?
UPDATE EMP SET SAL = SAL + 1000, COMM = SAL*0.1;
sal = 11000, comm = 1000 .
Q. Why does the following comm& give a compilation error?
DROP TABLE &TABLE_NAME;
Variable names should start with an alphabet. Here the table name starts with an '&' symbol.
Q. What is the advantage of specifying WITH GRANT OPTION in the GRANT comm& in sql?
The privilege receiver can further grant the privileges he/she has obtained from the owner to any other user.
Q. What is the use of DESC in SQL?
Answer:DESC has two purposes. It is used to describe a schema as well as to retrieve rows from table in descending order.
Explanation :
The query SELECT * FROM EMP ORDER BY ENAME DESC will display the output sorted on ENAME in descending order.
Q. What is the use of CASCADE CONSTRAINTS?
When this clause is used with the DROP comm&, a parent table can be dropped even when a child table exists.

SQL interview question and answers

SQL interview question and answers
SQL
SQL is an English like language consisting of commands to store, retrieve, maintain & regulate access to your database.

SQL*Plus
SQL*Plus is an application that recognizes & executes SQL commands & specialized SQL*Plus commands that can customize reports, provide help & edit facility & maintain system variables.

NVL
NVL : Null value function converts a null value to a non-null value for the purpose of evaluating an expression. Numeric Functions accept numeric I/P & return numeric values. They are MOD, SQRT, ROUND, TRUNC & POWER.

Date Functions
Date Functions are ADD_MONTHS, LAST_DAY, NEXT_DAY, MONTHS_BETWEEN & SYSDATE.

Character Functions
Character Functions are INITCAP, UPPER, LOWER, SUBSTR & LENGTH. Additional functions are GREATEST & LEAST. Group Functions returns results based upon groups of rows rather than one result per row, use group functions. They are AVG, COUNT, MAX, MIN & SUM.

TTITLE & BTITLE
TTITLE & BTITLE are commands to control report headings & footers.

COLUMN
COLUMN command define column headings & format data values.

BREAK
BREAK command clarify reports by suppressing repeated values, skipping lines & allowing for controlled break points.

COMPUTE
command control computations on subsets created by the BREAK command.

SET
SET command changes the system variables affecting the report environment.

SPOOL
SPOOL command creates a print file of the report.

JOIN
JOIN is the form of SELECT command that combines info from two or more tables.
Types of Joins are Simple (Equijoin & Non-Equijoin), Outer & Self join.
Equijoin returns rows from two or more tables joined together based upon a equality condition in the WHERE clause.
Non-Equijoin returns rows from two or more tables based upon a relationship other than the equality condition in the WHERE clause.
Outer Join combines two or more tables returning those rows from one table that have no direct match in the other table.
Self Join joins a table to itself as though it were two separate tables.

Union
Union is the product of two or more tables.

Intersect
Intersect is the product of two tables listing only the matching rows.

Minus
Minus is the product of two tables listing only the non-matching rows.

Correlated Subquery
Correlated Subquery is a subquery that is evaluated once for each row processed by the parent statement. Parent statement can be Select, Update or Delete. Use CRSQ to answer multipart questions whose answer depends on the value in each row processed by parent statement.

Multiple columns
Multiple columns can be returned from a Nested Subquery.

Sequences
Sequences are used for generating sequence numbers without any overhead of locking. Drawback is that after generating a sequence number if the transaction is rolled back, then that sequence number is lost.

Synonyms
Synonyms is the alias name for table, views, sequences & procedures and are created for reasons of Security and Convenience.
Two levels are Public - created by DBA & accessible to all the users. Private - Accessible to creator only. Advantages are referencing without specifying the owner and Flexibility to customize a more meaningful naming convention.

Indexes
Indexes are optional structures associated with tables used to speed query execution and/or guarantee uniqueness. Create an index if there are frequent retrieval of fewer than 10-15% of the rows in a large table and columns are referenced frequently in the WHERE clause. Implied tradeoff is query speed vs. update speed. Oracle automatically update indexes. Concatenated index max. is 16 columns.

Data types
Max. columns in a table is 255. Max. Char size is 255, Long is 64K & Number is 38 digits.
Cannot Query on a long column.
Char, Varchar2 Max. size is 2000 & default is 1 byte.
Number(p,s) p is precision range 1 to 38, s is scale -84 to 127.
Long Character data of variable length upto 2GB.
Date Range from Jan 4712 BC to Dec 4712 AD.
Raw Stores Binary data (Graphics Image & Digitized Sound). Max. is 255 bytes.
Mslabel Binary format of an OS label. Used primarily with Trusted Oracle.

Order of SQL statement execution
Where clause, Group By clause, Having clause, Order By clause & Select.

Transaction
Transaction is defined as all changes made to the database between successive commits.

Commit
Commit is an event that attempts to make data in the database identical to the data in the form. It involves writing or posting data to the database and committing data to the database. Forms check the validity of the data in fields and records during a commit. Validity check are uniqueness, consistency and db restrictions.

Posting
Posting is an event that writes Inserts, Updates & Deletes in the forms to the database but not committing these transactions to the database.

Rollback
Rollback causes work in the current transaction to be undone.

Savepoint

Savepoint is a point within a particular transaction to which you may rollback without rolling back the entire transaction.

Set Transaction
Set Transaction is to establish properties for the current transaction.

Locking
Locking are mechanisms intended to prevent destructive interaction between users accessing data. Locks are used to achieve.

Consistency
Consistency : Assures users that the data they are changing or viewing is not changed until the are thro' with it.

Integrity
Assures database data and structures reflects all changes made to them in the correct sequence. Locks ensure data integrity and maximum concurrent access to data. Commit statement releases all locks. Types of locks are given below.
Data Locks protects data i.e. Table or Row lock.
Dictionary Locks protects the structure of database object i.e. ensures table's structure does not change for the duration of the transaction.
Internal Locks & Latches protects the internal database structures. They are automatic.
Exclusive Lock allows queries on locked table but no other activity is allowed.
Share Lock allows concurrent queries but prohibits updates to the locked tables.
Row Share allows concurrent access to the locked table but prohibits for a exclusive table lock.
Row Exclusive same as Row Share but prohibits locking in shared mode.
Shared Row Exclusive locks the whole table and allows users to look at rows in the table but prohibit others from locking the table in share or updating them.
Share Update are synonymous with Row Share.

Deadlock
Deadlock is a unique situation in a multi user system that causes two or more users to wait indefinitely for a locked resource. First user needs a resource locked by the second user and the second user needs a resource locked by the first user. To avoid dead locks, avoid using exclusive table lock and if using, use it in the same sequence and use Commit frequently to release locks.

Mutating Table
Mutating Table is a table that is currently being modified by an Insert, Update or Delete statement. Constraining Table is a table that a triggering statement might need to read either directly for a SQL statement or indirectly for a declarative Referential Integrity constraints. Pseudo Columns behaves like a column in a table but are not actually stored in the table. E.g. Currval, Nextval, Rowid, Rownum, Level etc.

SQL*Loader
SQL*Loader is a product for moving data in external files into tables in an Oracle database. To load data from external files into an Oracle database, two types of input must be provided to SQL*Loader : the data itself and the control file. The control file describes the data to be loaded. It describes the Names and format of the data files, Specifications for loading data and the Data to be loaded (optional). Invoking the loader sqlload username/password controlfilename .

Command is used to create a table by copying the structure of another table?

Command is used to create a table by copying the structure of another table?
Command: CREATE TABLE .. AS SELECT command
Explanation :
To copy only the structure, the WHERE clause of the SELECT command should
contain a FALSE statement as in the following.
CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE
WHERE 1=2;
If the WHERE condition is true, then all the rows or rows satisfying the condition
will be copied to the new table.

What is a global variable in SQL?

What is a global variable in SQL?
A global variable is a variable that does not belong to any Stored Proecdure or trigger, cursor and can be accessed from anywhere in a database by any stored procedure or trigger, cursor.

What are locks in SQL?

What are locks in SQL?
There are three main types of locks that SQL Server 7.0/2000 uses:
• Shared locks
• Update locks
• Exclusive locks
Shared locks are used for operations that do not change or update data, such as a SELECT statement.
Update locks are used when SQL Server intends to modify a page, and later promotes the update page lock to an exclusive page lock before actually making the changes.
Exclusive locks are used for the data modification operations, such as UPDATE, INSERT, or DELETE.

What is SQL profiling?

What is SQL profiling?
SQL Server Profiler is a tool that captures SQL Server 2005 events from a server. The events are saved in a trace file that can later be analyzed or used to replay a specific series of steps when trying to diagnose a problem. SQL Server Profiler is used for activities such as:
Stepping through problem queries to find the cause of the problem.
Finding and diagnosing slow-running queries.
Capturing the series of Transact-SQL statements that lead to a problem. The saved trace can then be used to replicate the problem on a test server where the problem can be diagnosed.
Monitoring the performance of SQL Server to tune workloads. For information about tuning the physical database design for database workloads.
Correlating performance counters to diagnose problems

Interview questions for database (common database questions)

Interview questions for database (common database questions)
1. What are the different types of joins?
2. Explain normalization with examples.
3. What cursor type do you use to retrieve multiple recordsets?
4. Diffrence between a "where" clause and a "having" clause
5. What is the difference between "procedure" and "function"?
6. How will you copy the structure of a table without copying the data?
7. How to find out the database name from SQL*PLUS command prompt?
8. Tadeoffs with having indexes
9. Talk about "Exception Handling" in PL/SQL?
10. What is the diference between "NULL in C" and "NULL in Oracle?"
11. What is Pro*C? What is OCI?
12. Give some examples of Analytical functions.
13. What is the difference between "translate" and "replace"?
14. What is DYNAMIC SQL method 4?
15. How to remove duplicate records from a table?
16. What is the use of ANALYZing the tables?
17. How to run SQL script from a Unix Shell?
18. What is a "transaction"? Why are they necessary?
19. Explain Normalizationa dn Denormalization with examples.
20. When do you get contraint violtaion? What are the types of constraints?
21. How to convert RAW datatype into TEXT?
22. Difference - Primary Key and Aggregate Key
23. How functional dependency is related to database table design?
24. What is a "trigger"?
25. Why can a "group by" or "order by" clause be expensive to process?
26. What are "HINTS"? What is "index covering" of a query?
27. What is a VIEW? How to get script for a view?
28. What are the Large object types suported by Oracle?
29. What is SQL*Loader?
30. Difference between "VARCHAR" and "VARCHAR2" datatypes.
31. What is the difference among "dropping a table", "truncating a table" and "deleting all records" from a table.
32. Difference between "ORACLE" and "MICROSOFT ACCESS" databases.
33. How to create a database link ?