Cracking The SQL Interview
Cracking The SQL Interview
Sajjad Salaria
However, to be compliant with the ANSI standard, they all support at least
the major commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE)
in a similar manner.
Note: Most of the SQL database programs also have their own proprietary
extensions in addition to the SQL standard!
4
2. What does SQL stand for?
SQL stands for Structured Query Language.
5
5. What is MySQL?
MySQL is the most popular Open Source SQL database management
system developed, distributed, and supported by Oracle Corporation.
SQL may be considered as the source of data for our reports, web pages
and screens.
SQL is a data oriented language used to select and manipulate sets of data.
SQL is declarative, i.e., it tells the database what to do but not how to do it.
6
7. What are the possible values for the BOOLEAN data field in MySQL?
MySQL uses TINYINT(1) data type to represent boolean values. A value
of zero is considered false . Non-zero values are considered true .
8. What data type would you choose if you wanted to store the distance
(rounded to the nearest mile)?
INTEGER (or INT )
WHERE - clause is used to extract only those records that fulfill a specified
condition.
7
10. Which of the following are valid SQL comments?
Comments are used to explain sections of SQL statements, or to prevent
execution of SQL statements.
Any text between -- and the end of the line will be ignored (will not be
executed).
• --Select all:
8
12. How to select all records from the table 'Products'?
SELECT * FROM Products;
If you want to select all the fields available in the table, use the * syntax as
this:
• FROM table_name;
14. With SQL, how do you select a column named "FirstName" from a
table named "Customers"?
SELECT FirstName FROM Customers;
SELECT Syntax
9
15. What does the SQL FROM clause do?
The SQL FROM clause is used to list the tables and any joins required for
the SQL statement.
18. With SQL, how do you select all the records from a table named
"Customers" where the value of the column "FirstName" is "John"?
SELECT * FROM Customers WHERE FirstName='John';
SQL requires single quotes around text values (most database systems will
also allow double quotes).
10
19. The OR operator displays a record if ANY conditions listed are true.
The AND operator displays a record if ALL of the conditions listed are
true.
The WHERE clause can be combined with AND , OR , and NOT operators.
AND Syntax
= Equal to
21. With SQL, how do you select all the records from a table named
"Customers" where the "FirstName" is "John" and the "LastName" is
"Jackson"?
SELECT * FROM Customers WHERE FirstName='John' AND
LastName='Jackson'
You must use the AND operator that displays a record if all the conditions
separated by AND are TRUE and the = (‘equal’) comparison operator.
12
22. How to select random 10 rows from a table?
The easiest way to generate random rows in MySQL is to use the ORDER BY
RAND() clause.
This can work fine for small tables. However, for big table, it will have a
serious performance problem as in order to generate the list of random rows,
MySQL need to assign random number to each row and then sort them.
Even if you want only 10 random rows from a set of 100k rows, MySQL need
to sort all the 100k rows and then, extract only 10 of them.
23. Examine the following code. What will the value of price be if the
statement finds a NULL value? SELECT name, ISNULL(price, 50) FROM
PRODUCTS
What is a NULL Value?
13
How can you return a default value for a NULL?
MySQL
Examples:
25. How to write a query to show the details of a student from Students
table whose FirstName starts with 'K'?
SELECT * FROM Students WHERE FirstName LIKE 'K%'.
15
26. Which operator is used to select values within a range?
The BETWEEN operator selects values within a given range. The values can
be numbers, text, or dates.
BETWEEN Syntax
• SELECT column_name(s)
• FROM table_name
• WHERE column_name BETWEEN value1 AND value2;
28. With SQL, how do you select all the records from a table named
"Customers" where the "LastName" is alphabetically between (and
including) "Brooks" and "Gray"?
SELECT * FROM Customers WHERE LastName BETWEEN 'Brooks'
AND 'Gray'
16
29. The 'IN' SQL keyword…
The IN operator allows you to specify multiple values in a WHERE clause.
IN Syntax
• SELECT column_name(s)
• FROM table_name
• WHERE column_name IN (value1, value2, ...);
or:
• SELECT column_name(s)
• FROM table_name
• WHERE column_name IN (SELECT STATEMENT); --subquery
31. What function to use to round a number to the smallest integer value
that is greater than or equal to a number?
The CEILING() function returns the smallest integer value that is greater
than or equal to the specified number.
Example:
17
32. How to get current date in MySQL (without time)?
The CURDATE() function returns the current date. This function returns the
current date as a YYYY-MM-DD format if used in a string context, and as
a YYYYMMDD format if used in a numeric context.
MAX() Syntax
• SELECT MAX(column_name)
• FROM table_name
• WHERE condition;
COUNT() Syntax
• SELECT COUNT(column_name)
• FROM table_name
• WHERE condition;
18
35. Which of the following are Aggregate Functions?
SQL Aggregate functions are:
36. With SQL, how can you return the number of records in the
"Customers" table?
SELECT COUNT(*) FROM Customers
37. Which 2 SQL keywords specify the sorting direction of the result set
retrieved with ORDER BY clause?
ASC | DESC
ORDER BY Syntax
19
38. If you don't specify ASC or DESC for an ORDER BY clause, the
following is used by default:
The ORDER BY keyword sorts the records in ascending order by default. To
sort the records in descending order, use the DESC keyword.
39. Suppose a Students table has two columns, name and mark. How to
get name and mark of top three students?
SELECT name, mark FROM Students ORDER BY mark DESC LIMIT
3;
You have to use ORDER BY to order students by their marks and then select
just the first 3 records.
40. With SQL, how can you return all the records from a table named
"Customers" sorted descending by "FirstName"?
SELECT * FROM Customers ORDER BY FirstName DESC;
20
41. Which of the following SQL statements is correct?
SELECT name, COUNT(name) FROM customers GROUP BY name
42. What is the difference between HAVING clause and WHERE clause?
Both specify a search condition but HAVING clause is used only with
the SELECT statement and typically used with GROUP BY clause.
21
45. What are different JOINS used in SQL?
There are several types of joins:
The LEFT JOIN keyword returns all records from the left table (table1), and
the matched records from the right table (table2). The result is NULL from
the right side, if there is no match.
The RIGHT JOIN keyword returns all records from the right table (table2),
and the matched records from the left table (table1). The result
is NULL from the left side, when there is no match.
The FULL OUTER JOIN keyword return all records when there is a match in
either left (table1) or right (table2) table records.
A self JOIN is a regular join, but the table is joined with itself.
The SQL CROSS JOIN produces a result set which is the number of rows in
the first table multiplied by the number of rows in the second table if
no WHERE clause is used along with CROSS JOIN .This kind of result is
called as Cartesian Product.
22
46. Which of the following is NOT TRUE about the ON clause?
ON clause is used to specify conditions or specify columns
to JOIN . ON clause makes the query easy to understand. ON clause allows
3 way (or more) joins.
For example, for a Faculty table the lookup tables might be Division, with
DivisionID as the PK, Country, with CountryID as the PK, and Nationality,
with NationalityID as the PK. To join Faculty to the Division, Country, and
Nationality tables, the fields DivisionID, CountryID and NationalityID would
need to be foreign keys in the Faculty table.
• SELECT column_name(s)
• FROM table1 T1, table1 T2
• WHERE condition;
The SQL CROSS JOIN produces a result set which is the number of rows in
the first table multiplied by the number of rows in the second table if
no WHERE clause is used along with CROSS JOIN .This kind of result is
called as Cartesian Product.
• SELECT *
• FROM table1
• CROSS JOIN table2;
24
51. In relational algebra the INTERSECTION of two sets (set A and Set
B) corresponds to
A AND B
INTERSECT Syntax
A OR B
Union Syntax
UNION ALL – returns all rows selected by either query, including all
duplicates.
26
54. Having a list of Customer Names that searched for product 'X' and a
list of customer Names that bought the product 'X'. What set operator
would you use to get only those who are interested but did not bought
product 'X' yet?
MINUS
MINUS Syntax
Subquery.
• A SELECT clause
• A FROM clause
• A WHERE clause
You can use the comparison operators, such as > , < , or = . The comparison
operator can also be a multiple-row operator, such as IN , ANY , or ALL .
A subquery is also called an inner query or inner select, while the statement
containing a subquery is also called an outer query or outer select.
The inner query executes first before its parent query so that the results of an
inner query can be passed to the outer query.
28
59. A subquery that uses a correlation name from the outer query is
called a
If the output of a subquery is depending on column values of the parent
query table then the query is called Correlated Subquery.
CASE Syntax
• CASE expression
• WHEN condition1 THEN result1
• WHEN condition2 THEN result2
• ...
• WHEN conditionN THEN resultN
• ELSE result
• END
29
62. Which of the following SQL statements are DDL
ALTER Statements
CREATE Statements
DROP Statements
TRUNCATE TABLE
SELECT
INSERT
UPDATE
DELETE
GRANT : Used to provide any user access privileges or other privileges for
the database.
30
65. Which of the following is not a DML statement?
Same answer as for the previous questions.
67. When inserting data in a table do you have to specify the list of
columns you are inserting values for?
The first way specifies both the column names and the values to be inserted:
68. With SQL, how can you insert a new record into the "Customers"
table?
Same answer as for the previous question.
69. With SQL, how can you insert "Hawkins" as the "LastName" in the
"Customers" table?
Same answer as for the previous question.
31
70. How do you create a temporary table in MySQL?
To create a temporary table, you just need to add the TEMPORARY keyword
to the CREATE TABLE statement.
Example:
UPDATE Syntax
• UPDATE table_name
• SET column1 = value1, column2 = value2, ...
• WHERE condition;
72. What is the keyword is used in an UPDATE query to modify the
existing value?
UPDATE Syntax
• UPDATE table_name
• SET column1 = value1, column2 = value2, ...
• WHERE condition;
73. How can you change "Jackson" into "Hawkins" in the "LastName"
column in the Customer table?
32
DELETE Syntax
75. With SQL, how can you delete the records where the "FirstName" is
"John" in the Customers Table?
DELETE FROM Customers WHERE FirstName = 'John'
DELETE Syntax
• UPDATE table_name
• SET column1 = value1, column2 = value2, ...
• WHERE condition;
INSERT Syntax
Syntax
Detailed Explanation:
Suppose that we want to compare two string values, A and B. The simplest
way to do this is to look at the encodings: 0 for A and 1 for B. Because 0 is
less than 1, we say A is less than B. What we've just done is apply a
collation to our character set. The collation is a set of rules (only one rule in
this case): “compare the encodings.” We call this simplest of all possible
collations a binary collation.
But what if we want to say that the lowercase and uppercase letters are
equivalent? Then we would have at least two rules: (1) treat the lowercase
letters a and b as equivalent to A and B; (2) then compare the encodings. We
call this a case-insensitive collation. It is a little more complex than a binary
collation.
In real life, most character sets have many characters: not just A and B but
whole alphabets, sometimes multiple alphabets or eastern writing systems
with thousands of characters, along with many special symbols and
punctuation marks. Also in real life, most collations have many rules, not just
for whether to distinguish lettercase, but also for whether to distinguish
accents (an “accent” is a mark attached to a character as in German Ö), and
for multiple-character mappings (such as the rule that Ö = OE in one of the
two German collations).
Source: dev.myslq.com
35
80. What is true about an AUTO_INCREMENT column in SQL?
AUTO_INCREMENT allows a unique number to be generated automatically
when a new record is inserted into a table. Often this is the primary key field
that we would like to be created automatically every time a new record is
inserted.
You will have to create an auto-increment field with the sequence object (this
object generates a number sequence).
• MINVALUE 1
• START WITH 1
• INCREMENT BY 1
• CACHE 10;
The code above creates a sequence object called seq_person, that starts
with 1 and will increment by 1. It will also cache up to 10 values for
performance. The cache option specifies how many sequence values will be
stored in memory for faster access.
To insert a new record into the "Persons" table, we will have to use the
nextval function (this function retrieves the next value from seq_person
sequence):
Constraints are used to limit the type of data that can go into a table. This
ensures the accuracy and reliability of the data in the table. If there is any
violation between the constraint and the data action, the action is aborted.
37
CHECK - Ensures that all values in a column satisfies a specific condition
INDEX - Used to create and retrieve data from the database very quickly
83. The NOT NULL constraint enforces a column to not accept null
values.
NOT NULL - Ensures that a column cannot have a NULL value.
38
85. What is CHECK Constraint?
The CHECK constraint is used to limit the value range that can be placed in
a column.
MySQL:
Syntax
40
89. How do you add a 'order_date' column to a table called 'order'?
ALTER TABLE order ADD order_date DATE
Syntax
To delete a column in a table, use the following syntax (notice that some
database systems don't allow deleting a column):
Note: Updating a table with indexes takes more time than updating a table
without (because the indexes also need an update). So, only create indexes
on columns that will be frequently searched against.
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.
Syntax
• GRANT privilege_name
• ON object_name
• TO {user_name|PUBLIC|role_name}
• [WITH GRANT OPTION];
In above syntax WITH GRANT OPTIONS indicates that the user can grant
the access to another user too.
Syntax
• REVOKE privilege_name
• ON object_name
• FROM {user_name|PUBLIC|role_name};
43
95. How many types of Privileges are available in SQL?
There are two types of privileges used in SQL, such as
96. List the various privileges that a user can grant to another user?
Same answers as for the previous question
44
98. What are a transaction's main controls?
COMMIT command is used to permanently save any transaction into the
database.
COMMIT;
ROLLBACK command
This command restores the database to last committed state. It is also used
with SAVEPOINT command to jump to a savepoint in an ongoing
transaction.
ROLLBACK TO savepoint_name;
SAVEPOINT command
45
Following is savepoint command syntax:
SAVEPOINT savepoint_name;
In short, using this command we can name the different states of our data in
any table and then rollback to that state using the ROLLBACK command
whenever required.
Committed.
46
101. What are valid properties of the transaction?
The characteristics of these four properties as defined by Reuter and Härder
are as follows:
Atomicity
Atomicity requires that each transaction be "all or nothing": if one part of the
transaction fails, then the entire transaction fails, and the database state is
left unchanged. An atomic system must guarantee atomicity in each and
every situation, including power failures, errors and crashes. To the outside
world, a committed transaction appears (by its effects on the database) to be
indivisible ("atomic"), and an aborted transaction does not happen.
Consistency
The consistency property ensures that any transaction will bring the
database from one valid state to another. Any data written to the database
must be valid according to all defined rules, including constraints, cascades,
triggers, and any combination thereof. This does not guarantee correctness
of the transaction in all ways the application programmer might have wanted
(that is the responsibility of application-level code), but merely that any
programming errors cannot result in the violation of any defined rules.
Isolation
Durability
The durability property ensures that once a transaction has been committed,
it will remain so, even in the event of power loss, crashes, or errors. In a
relational database, for instance, once a group of SQL statements execute,
the results need to be stored permanently (even if the database crashes
immediately thereafter). To defend against power loss, transactions (or their
effects) must be recorded in a non-volatile memory.
47
102. What happens if autocommit is enabled?
If autocommit mode is enabled, each SQL statement forms a single
transaction on its own. By default, most of DBMS start the session for each
new connection with autocommit enabled, so they do a commit after each
SQL statement if that statement did not return an error. If a statement returns
an error, the commit or rollback behavior depends on the error.
TRUE
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.
All views are not updatable. So, UPDATE command is not applicable to all
views. An updatable view is one which allows performing a UPDATE
command on itself without affecting any other table.
2. The view must include the PRIMARY KEY of the table based upon which
the view has been created.
3. The view should not have any field made out of aggregate functions.
7. If the view you want to update is based upon another view, the later
should be updatable.
8. Any of the selected output fields (of the view) must not use constants,
strings or value expressions.
49
107. What are the advantages of Views?
Simplify queries: You can use database view to hide the complexity of
underlying tables to the end-users and external applications
A database view helps limit data access to specific users. You may not want
a subset of sensitive data can be queryable by all users
The answer depends on the type of view. In case of normal view, the answer
is NO it only contains query based on a base table but in case of
materialized view, YES it does contain data and for the updated data in the
base table, it needs to be refreshed.
50
111. Inside a stored procedure you to iterate over a set of rows returned
by a query using a
A CURSOR is a database object which is used to manipulate data in a row-
to-row manner.
• Declare Cursor
• Open Cursor
• Close Cursor
• Deallocate Cursor
112. How do you call the process of finding a good strategy for
processing a query?
Query optimization is a function of many relational database management
systems. The query optimizer attempts to determine the most efficient way
to execute a given query by considering the possible query plans.
51
113. What is a trigger?
Triggers in SQL is kind of stored procedures used to create a response to a
specific action performed on the table. You can invoke triggers explicitly on
the table in the database.
Action and Event are two main components of SQL triggers when certain
actions are performed the event occurs in response to that action.
Syntax
52
116. A special kind of a stored procedure that executes in response to
certain action on the table like insertion, deletion or updation of data is
called
Trigger.
SQL injection is a code injection technique that might destroy your database.
SQL injection is the placement of malicious code in SQL statements, via web
page input.
Resources
www.wikipedia.org
www.w3schools.com
www.freefeast.info