SQL Interview Questions PDF
SQL Interview Questions PDF
1. What is Database?
A database is a system that helps in collecting, storing and retrieving data. Databases can be
complex, and such databases are developed using design and modelling approaches.
2. What is DBMS?
DBMS stands for Database Management System which is responsible for the creating,
updating, and managing of the database.
RDBMS stands for Relational Database Management System that stores data in the form of a
collection of tables, and relations can be defined between the common fields of these tables.
4. What is SQL?
SQL stands for Structured Query Language. It is the primary language to interact with
databases. With the help of SQL, we can extract data from a database, modify this data and
also update it whenever there is a requirement. This query language is evergreen and is widely
used across industries. For example, if a company has records of all the details of their
employees in the database. With the help of SQL, all of this data can be queried to find out
valuable insights in a short span of time.
[optin-monster slug="ctrmdyfijdpf2ssxvejn"]
We will start off by giving the keywords, CREATE TABLE, then we will give the name of the
table. After that in braces, we will list out all the columns along with their datatypes.
For example, if we want to create a simple employee table:
There are two ways to delete a table from sql: DROP and TRUNCATE. The DROP TABLE
command is used to completely delete the table from the database. This is the command:
The above command will completely delete all the data present in the table along with the table
itself.
But if we want to delete only the data present in the table but not the table itself, then we will use
the truncate command:
RENAME TO new_table_name;
We will start off by giving the keywords ALTER TABLE, then we will follow it up by giving the
original name of the table, after that, we will give in the keywords RENAME TO and finally, we
will give the new table name.
For example, if we want to change the “employee” table to “employee_information”, this will be
the command:
RENAME TO employee_information;
To be more thorough with your preparation, do check out our Free Course on SQL Interview
Questions at Great Learning Academy. In this course, we start off with interview questions on
the basics of SQL. Then, we dive into the questions of Normalization and Sub-queries. Finally,
we have interview questions on two projects "Broadband management system" and "HR
DBMS". You can also take up the software engineer certificate course offered by Great Learning
in collaboration with leading universities. Great Learning offers career assistance and dedicated
mentor support to help power ahead your career.
We will be using the DELETE query to delete existing rows from the table:
WHERE [condition];
We will start off by giving the keywords DELETE FROM, then we will give the name of the table,
after that we will give the WHERE clause and give the condition on the basis of which we would
want to delete a row.
For example, from the employee table, if we would like to delete all the rows, where the age of
the employee is equal to 25, then this will the command:
WHERE [age=25];
https://youtu.be/gKtqrpfBM28
Normalization is used to decompose a larger, complex table into simple and smaller ones. This
helps us in removing all the redundant data.
Generally, in a table, we will have a lot of redundant information which is not required, so it is
better to divide this complex table into multiple smaller tables which contains only unique
information.
It is in 2NF.
No transitive dependency exists between non-key attributes and key attributes through another
non-key attribute
[ays_quiz id='5']
Joins are used to combine rows from two or more tables, based on a related column between
them.
Types of Joins:
•LEFT JOIN − Returns all rows from the left table, even if there are no matches in the right
table.
•RIGHT JOIN − Returns all rows from the right table, even if there are no matches in the left
table.
•FULL OUTER JOIN − Returns rows when there is a match in one of the tables.
•SELF JOIN − Used to join a table to itself as if the table were two tables, temporarily renaming
at least one table in the SQL statement.
•CARTESIAN JOIN (CROSS JOIN) − Returns the Cartesian product of the sets of records from
the two or more joined tables.
INNER JOIN:
The INNER JOIN creates a new result table by combining column values of two tables (table1
and table2) based upon the join-predicate. The query compares each row of table1 with each
row of table2 to find all pairs of rows which satisfy the join-predicate.
SYNTAX :
LEFT JOIN:
The LEFT JOIN returns all the values from the left table, plus matched values from the right
table or NULL in case of no matching join predicate.
SYNTAX :
RIGHT JOIN:
The RIGHT JOIN returns all the values from the right table, plus matched values from the left
table or NULL in case of no matching join predicate.
SYNTAX :
SYNTAX :
SELF JOIN:
The SELF JOIN joins a table to itself; temporarily renaming at least one table in the SQL
statement.
SYNTAX:
To understand what exactly is SQL Server, we need to understand what is DBMS and RDBMS.
DBMS stands for Database Management System. When we have a huge database with us, we
would need a proper management system which would help us organise this database. There
are 4 types of database management systems:
● Hierarchical
● Network
● Relational
● Object-Oriented.
Out of these database management systems, SQL Server comes under the category of
Relational database management system. A relational database refers to a database that
stores data in a structured format, using rows and columns. This makes it easier to locate and
access specific values within the database. It is "relational" because the values within each
table are related to each other. The relational structure makes it possible to run queries across
multiple tables at once.
10. How to insert date in SQL?
"INSERT INTO tablename (col_name, col_date) VALUES ('DATE: Manual Date', '2020-9-10')";
Primary Key is a constraint in SQL. So, before understanding what exactly is a primary key, let’s
understand what exactly is a constraint in SQL. Constraints are the rules enforced on data
columns on a table. These are used to limit the type of data that can go into a table. Constraints
can either be column level or table level.
Let’s look at the different types of constraints which are present in SQL:
Constraint Description
CHECK The CHECK constraint ensures that all values in a column satisfy
certain conditions.
INDEX Used to create and retrieve data from the database very quickly.
You can consider Primary Key constraint to be a combination of UNIQUE and NOT NULL
constraint. This means that if a column is set as a primary key, then this particular column
cannot have any null values present in it and also all the values present in this column must be
unique.
Show tables;
PL SQL stands for Procedural language constructs for Structured Query Language. PL SQL
was introduced by Oracle to overcome the limitations of plain sql. So, pl sql adds in procedural
language approach to the plain vanilla sql.
One thing to be noted over here is that pl sql is only for oracle databases. If you don’t have an
Oracle database, then you cant work with PL SQL.
While, with the help of sql, we were able to DDL and DML queries, with the help of PL SQL, we
will be able to create functions, triggers and other procedural constructs.
To understand exactly what is MYSQL, we need to understand what is DBMS and RDBMS.
DBMS stands for Database Management System. When we have a huge database with us, we
would need a proper management system which would help us organise this database. There
are 4 types of database management systems:
● Hierarchical
● Network
● Relational
● Object - Oriented.
Out of these database management systems, MYSQL comes under the category of Relational
database management system. A relational database refers to a database that stores data in a
structured format, using rows and columns. This makes it easier to locate and access specific
values within the database. It is "relational" because the values within each table are related to
each other. The relational structure makes it possible to run queries across multiple tables at
once.
Different database management systems have different queries to see all the tables.
To see all the tables in MYSQL, we would have to use this query:
show tables;
SELECT
table_name
FROM
User_tables;
SELECT
*
FROM
Information_schema.tables;
ETL stands for Extract, Transform and Load. It is a three step process, where we would have to
start off by extracting the data from sources. Once we collate the data from different sources,
what we have is raw data. This raw data has to be transformed into tidy format, which will come
in the second phase. Finally, we would have to load this tidy data into tools which would help us
to find insights.
SQL stands for Structured Query Language and it is not something you can install. To
implement sql queries, you would need a relational database management system. There are
different varieties of relational database management systems such as:
● ORACLE
● MYSQL
● SQL Server
Hence, to implement sql queries, we would need to install any of these Relational Database
Management Systems.
The update command comes under the DML(Data Manipulation Langauge) part of sql and is
used to update the existing data in the table.
UPDATE employees
SET last_name=‘Cohen’
WHERE employee_id=101;
With this update command, I am changing the last name of the employee.
19. How to rename column name in SQL Server?
When it comes to SQL Server, it is not possible to rename the column with the help of ALTER
TABLE command, we would have to use sp_rename.
Command Description
Triggers may implement DML by using INSERT, UPDATE, and DELETE statements. These
triggers that contain DML and find other triggers for data modification are called Nested
Triggers.
23. Write SQL query to fetch employee names having a salary greater than
or equal to 20000 and less than or equal 10000.
By using BETWEEN in the where clause, we can retrieve the Employee Ids of employees with
salary >= 20000and <=10000. SELECT FullName FROM EmployeeDetails WHERE EmpId IN
(SELECT EmpId FROM EmployeeSalary WHERE Salary BETWEEN 5000 AND 10000)
24. Given a table Employee having columns empName and empId, what will
be the result of the SQL query below? select empName from Employee
order by 2 asc;
"Order by 2" is valid when there are at least 2 columns used in SELECT statement. Here this
query will throw error because only one column is used in the SELECT statement.
OLTP stands for Online Transaction Processing. And is a class of software applications capable
of supporting transaction-oriented programs. An essential attribute of an OLTP system is its
ability to maintain concurrency.
Data Integrity is the assurance of accuracy and consistency of data over its entire life-cycle, and
is a critical aspect to the design, implementation and usage of any system which stores,
processes, or retrieves data. It also defines integrity constraints to enforce business rules on the
data when it is entered into an application or a database.
OLAP stands for Online Analytical Processing. And a class of software programs which are
characterized by relatively low frequency of online transactions. Queries are often too complex
and involve a bunch of aggregations.
There are so many times where user needs to find out the specific constraint information of the
table. following queries are useful, SELECT * From User_Constraints; SELECT * FROM
User_Cons_Columns;
29. Can you get the list of employees with same salary?
1. ROWCOUNT function
2. Set rowcount 3
31. Will following statement give error or 0 as output? SELECT AVG (NULL)
The output of Cross Join is called a Cartesian product. It returns rows combining each row from
the first table with each row of the second table. For Example, if we join two tables having 15
and 20 columns the Cartesian product of two tables will be 15×20=300 rows.
Our database comprises of a lot of different entities such as tables, stored procedures,
functions, database owners and so on. To make sense of how all these different entities
interact, we would need the help of schema. So, you can consider schema to be the logical
relationship between all the different entities which are present in the database.
Once we have a clear understanding of the schema, this helps in a lot of ways:
● We can decide which user has access to which tables in the database.
● We can modify or add new relationships between different entities in the database.
Overall, you can consider a schema to be a blueprint for the database, which will give you the
complete picture of how different objects interact with each other and which users have access
to different entities.
The ‘Where’ clause is used to extract elements from the table on the basis of a condition.
As, you see, we have extracted all the records, where the value of ‘Sepal.Length’ is greater than
6.
Similarly, if you want to extract all records where ‘Species’ is Virginia, this will be the query:
We will start off by giving the keywords ALTER TABLE, then we will give the name of the table,
following which we will give the keywords DROP COLUMN and finally give the name of the
column which we would want to remove.
Unique Key is a constraint in SQL. So, before understanding what exactly is a primary key, let’s
understand what exactly is a constraint in SQL. Constraints are the rules enforced on data
columns on a table. These are used to limit the type of data that can go into a table. Constraints
can either be column level or table level.
Unique Key:
Whenever we give the constraint of unique key to a column, this would mean that the column
cannot have any duplicate values present in it. In other words, all the records which are present
in this column have to be unique.
[sc name="cards-style"][/sc]
Our Most Popular Courses:
><
[sc name="glcard" course_url="https://www.mygreatlearning.com/jain-online-master-of-
computer-applications" title="Online MCA"
image_url="https://d1vwxdpzbgdqj.cloudfront.net/assets/mba-jain-university/banner-
934a253656b25fa24773c958bb5bd4434360440de529a2846022f695e0c335de.png" time="2
Years" type="Live online classes"
institute_logo_url="https://d1vwxdpzbgdqj.cloudfront.net/assets/mba-jain-university/jain-logo-
90888a3ce4a9ded71c86a58d43d59f3fecd1573bebb6416fda2bf88174484e9c.png" ][/sc] [sc
name="glcard" course_url="https://www.mygreatlearning.com/post-graduate-diploma-csai-iiit-
delhi" title="IIIT-Delhi: Post Graduate Diploma in Computer Science and Artificial Intelligence"
image_url="https://d1vwxdpzbgdqj.cloudfront.net/assets/iiit-delhi/iiitd-pp-banner-
7daf977c7683a0a4e226c02c5746ea19b350604dbbe20bb2a6513d5a2ef36bdb.jpg" time="2
Years" type="Online Interactive Live Classes"
institute_logo_url="https://d1vwxdpzbgdqj.cloudfront.net/assets/iiit-delhi/iiitd-logo-
d434ecb9837c59ade75b2b154c5983f8552e15824b946633c202618853bc9d0a.png" ][/sc]
In the above command, we are giving two conditions. The condition ensures that we extract only
those records where the first name of the employee is ‘Steven’ and the second condition
ensures that the salary of the employee is less than $10,000. In other words, we are extracting
only those records, where the employee’s first name is ‘Steven’ and this person’s salary should
be less than $10,000.
You can refer this SQL beginner's tutorial if you want to know more about Structure
Query Language
https://www.youtube.com/watch?v=46bXJ55wNjQ
Learn In-Demand Skills for free on GL Academy
SQL injection is a hacking technique which is widely used by black-hat hackers to steal data
from your tables or databases. Let’s say, if you go to a website and give in your user information
and password, the hacker would add some malicious code over there such that, he can get the
user information and password directly from the database. If your database contains any vital
information, it is always better to keep it secure from SQL injection attacks.
We start off by giving the keywords INSERT INTO then we give the name of the table into which
we would want to insert the values. We will follow it up with the list of the columns, for which we
would have to add the values. Then we will give in the VALUES keyword and finally, we will give
the list of values.
(
'Bob',
26,
90000
);
In the above example, we are inserting multiple records into the table called employees.
This is how we can find the nth highest salary in SQL SERVER using TOP keyword:
SELECT TOP 1 salary FROM ( SELECT DISTINCT TOP N salary FROM #Employee ORDER
BY salary DESC ) AS temp ORDER BY salary
This is how we can find the nth highest salary in MYSQL using LIMIT keyword:
We can use the SELECT INTO statement to copy data from one table to another. Either we can
copy all the data or only some specific columns.
This is how we can copy all the columns into a new table:
SELECT *
INTO newtable
FROM oldtable
WHERE condition;
If we want to copy only some specific columns, we can do it this way:
We can add a new column in SQL with the help of alter command:
This command helps us to add a new column named as contact in the employees table.
The LIKE operator checks if an attribute value matches a given string pattern. Here is an
example of LIKE operator
With this command, we will be able to extract all the records where the first name is like
“Steven”.
Yes, SQL server drops all related objects, which exists inside a table like constraints, indexex,
columns, defaults etc. But dropping a table will not drop views and sorted procedures as they
exist outside the table.
Yes, we can disable a single trigger on the database by using "DISABLE TRIGGER
triggerName ON<> We also have an option to disable all the trigger by using, “DISABLE Trigger
ALL ON ALL SERVER”
A live lock is one where a request for an exclusive lock is repeatedly denied because a series of
overlapping shared locks keep interferring. A live lock also occurs when read transactions
create a table or page.
11. How to fetch alternate records from a table?
Records can be fetched for both Odd and Even row numbers- To display even numbers-. Select
employeeId from (Select rowno, employeeId from employee) where mod(rowno,2)=0 To display
odd numbers-. Select employeeId from (Select rowno, employeeId from employee) where
mod(rowno,2)=1
When a COMMIT is uded in a transaction all chnages made in the transaction are written into
the database permanently. Example: BEGIN TRANSACTION; DELETE FROM
HR.JobCandidate WHERE JobCandidateID = 20; COMMIT TRANSACTION; The above
example deletes a job candidate in a SQL server.
A table can be joined to itself using self join, when you want to create a result set that joins
records in a table with other records in the same table.
When two or more tables has been joined using equal to operator then this category is called as
equi join. Just we need to concentrate on condition is equal to(=) between the columns in the
table. Example: Select a.Employee_name,b.Department_name from Employee a,Employee b
where a.Department_ID=b.Department_ID
The SELECT DISTINCT is used to get distinct data from tables using a query. The below SQL
query selects only the DISTINCT values from the "Country" column in the "Customers" table:
SELECT DISTINCT Country FROM Customers;
16. How can you create an empty table from an existing table?
Lets take an example: Select * into studentcopy from student where 1=2 Here, we are copying
student table to another table with the same structure with no rows copied.
19. How can you delete duplicate records in a table with no primary key?
By using the SET ROWCOUNT command. It limits the number of records affected by a
command. Let's take an example, if you have 2 duplicate rows, you would SET ROWCOUNT 1,
execute DELETE command and then SET ROWCOUNT 0
Both the NVL(exp1, exp2) and NVL2(exp1, exp2, exp3) functions check the value exp1 to see if
it is null. With the NVL(exp1, exp2) function, if exp1 is not null, then the value of exp1 is
returned; otherwise, the value of exp2 is returned, but case to the same data type as that of
exp1. With the NVL2(exp1, exp2, exp3) function, if exp1 is not null, then exp2 is returned;
otherwise, the value of exp3 is returned.
2. Clustered indexes store data physically in the table or view whereas, non-clustered indexes
do not store data in the table as it has separate structure from the data row.
The given syntax indicates that the user can grant access to another user too.
It compresses the MyISAM tables, which reduces their disk or memory usage.
25. What is ISAM?
ISAM is abbreviated as Indexed Sequential Access Method. It was developed by IBM to store
and retrieve data on secondary storage systems like tapes.
White box testing includes: 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.
1. Safe Access Sandbox: Here a user can perform SQL operations such as creating stored
procedures, triggers etc. but cannot have access to the memory as well as cannot create files.
2. External Access Sandbox: Users can access files without having the right to manipulate the
memory allocation.
3. Unsafe Access Sandbox: This contains untrusted codes where a user can have access to
memory.
This testing involves 1. Data Mapping 2. Data stored and retrieved 3. Use of Black Box testing
techniques such as Equivalence Partitioning and Boundary Value Analysis (BVA).
This join is usable, when user wants all the records from Right table (Second table) and only
equal or matching records from First or left table. The unmatched records are considered as null
records. Example: Select t1.col1,t2.col2….t ‘n’col ‘n.’. from table1 t1,table2 t2 where
t1.col(+)=t2.col;
A SubQuery is a SQL query nested into a larger query. Example: SELECT employeeID,
firstName, lastName FROM employees WHERE departmentID IN (SELECT departmentID
FROM departments WHERE locationID = 2000) ORDER BY firstName, lastName;
There are multiple ways to find duplicate records in SQL. Let’s see how can we find duplicate
records using groupby:
SELECT
x,
y,
COUNT(*) occurrences
FROM z1
GROUP BY
x,
y
HAVING
COUNT(*) > 1;
If you have knowledge about other programming languages, then you’d have learnt about if-else
statements. You can consider Case WHEN to be analogous to that.
In Case WHEN, there will be multiple conditions and we will choose something on the basis of
these conditions.
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
We start off by giving the CASE keyword, then we follow it up by giving multiple WHEN, THEN
statements.
delete e
from emp e
inner join
(select *,
RANK() OVER ( PARTITION BY eid,ename ORDER BY id DESC )rank
From emp )T on e.sid=t.sid
where e.Rank>1
Below is the syntax to delete duplicate records using groupby and min:
Cursors in SQL are used to store database tables. There are two types of cursors:
● Implicit Cursor
● Explicit Cursor
Implicit Cursor:
These implicit cursors are default cursors which are automatically created. A user cannot create
an implicit cursor.
Explicit Cursor:
Explicit cursors are user-defined cursors. This is the syntax to create explicit cursor:
We start off by giving by keyword DECLARE, then we give the name of the cursor, after that we
give the keywords CURSOR FOR SELECT * FROM, finally, we give in the name of the table.
If you have worked with other languages, then you would know about the concept of Functions.
You can consider stored procedures in SQL to be analogous to functions in other languages.
This means that we can store a SQL statement as a stored procedure and this stored procedure
can be invoked whenever we want.
We start off by giving the keywords CREATE PROCEDURE, then we go ahead and give the
name of this stored procedure. After that, we give the AS keyword and follow it up with the SQL
query, which we want as a stored procedure. Finally, we give the GO keyword.
EXEC procedure_name;
We will give in the keyword EXEC and then give the name of the stored procedure.
With this, we are extracting all the employees who belong to Boston.
We start off by giving the keywords CREATE INDEX and then we will follow it up with the name
of the index, after that we will give the ON keyword. Then, we will give the name of the table on
which we would want to create this index. Finally, in parenthesis, we will list out all the columns
which will have the index. Let’s look at an example:
In the above example, we are creating an index called a salary on top of the ‘Salary’ column of
the ‘Employees’ table.
We start off with the keywords CREATE UNIQUE INDEX, then give in the name of the index,
after that, we will give the ON keyword and follow it up with the name of the table. Finally, in
parenthesis, we will give the list of the columns which on which we would want this unique
index.
[sc name="cards-style"][/sc]
Our Most Popular Courses:
><
[sc name="glcard" course_url="https://www.mygreatlearning.com/jain-online-master-of-
computer-applications" title="Online MCA"
image_url="https://d1vwxdpzbgdqj.cloudfront.net/assets/mba-jain-university/banner-
934a253656b25fa24773c958bb5bd4434360440de529a2846022f695e0c335de.png" time="2
Years" type="Live online classes"
institute_logo_url="https://d1vwxdpzbgdqj.cloudfront.net/assets/mba-jain-university/jain-logo-
90888a3ce4a9ded71c86a58d43d59f3fecd1573bebb6416fda2bf88174484e9c.png" ][/sc] [sc
name="glcard" course_url="https://www.mygreatlearning.com/post-graduate-diploma-csai-iiit-
delhi" title="IIIT-Delhi: Post Graduate Diploma in Computer Science and Artificial Intelligence"
image_url="https://d1vwxdpzbgdqj.cloudfront.net/assets/iiit-delhi/iiitd-pp-banner-
7daf977c7683a0a4e226c02c5746ea19b350604dbbe20bb2a6513d5a2ef36bdb.jpg" time="2
Years" type="Online Interactive Live Classes"
institute_logo_url="https://d1vwxdpzbgdqj.cloudfront.net/assets/iiit-delhi/iiitd-logo-
d434ecb9837c59ade75b2b154c5983f8552e15824b946633c202618853bc9d0a.png" ][/sc]
We can change the data-type of the column using the alter table. This will be the command:
We start off by giving the keywords ALTER TABLE, then we will give in the name of the table.
After that, we will give in the keywords MODIFY COLUMN. Going ahead, we will give in the
name of the column for which we would want to change the datatype and finally we will give in
the data type to which we would want to change.
SQL stands for structured query language and is majorly used to query data from relational
databases. When we talk about a SQL database, it will be a relational database.
But when it comes to NoSQL database, we will be working with non-relational databases.
IN MYSQL, we will start off by using the ALTER TABLE keywords, then we will give in the name
of the table. After that, we will use the CHANGE keyword and give in the original name of the
column, following which we will give the name to which we would want to rename our column.
In ORACLE, we will start off by using the ALTER TABLE keywords, then we will give in the
name of the table. After that, we will use the RENAME COLUMN keywords and give in the
original name of the column, following which we will give the TO keyword and finally give the
name to which we would like to rename our column.
When it comes to SQL Server, it is not possible to rename the column with the help of ALTER
TABLE command, we would have to use sp_rename.
A view is a database object that is created using a Select Query with complex logic, so views
are said to be a logical representation of the physical data, i.e Views behave like a physical
table and users can use them as database objects in any part of SQL queries.
● Simple View
● Complex View
● Inline View
● Materialized View
Simple View:
Simple views are created with a select query written using a single table. Below is the command
to create a simple view:
Complex View:
Inline View:
A subquery is also called as an inline view if and only if it is called in FROM clause of a SELECT
query.
We will start off by giving the keywords ALTER TABLE, then we will give the name of the table,
following which we will give the keywords DROP COLUMN and finally give the name of the
column which we would want to remove.
There are a lot of ways to remove duplicate rows in SQL. Let’s look at this example:
SELECT [Name],
[Age],
[Gender],
COUNT(*) AS CNT
FROM [mydata].[dbo].[Employees]
GROUP BY [Name],
[Age],
[Gender]
HAVING COUNT(*) > 1;
In the above command, we are using group by and having to count the duplicate records.
Joins are used to combine rows from two or more tables, based on a related column between
them.
Types of Joins:
•LEFT JOIN − Returns all rows from the left table, even if there are no matches in the right
table.
•RIGHT JOIN − Returns all rows from the right table, even if there are no matches in the left
table.
•FULL OUTER JOIN − Returns rows when there is a match in one of the tables.
•SELF JOIN − Used to join a table to itself as if the table were two tables, temporarily renaming
at least one table in the SQL statement.
•CARTESIAN JOIN (CROSS JOIN) − Returns the Cartesian product of the sets of records from
the two or more joined tables.
The BETWEEN operator checks an attribute value within a range. Here is an example of
BETWEEN operator:
With this command, we will be able to extract all the records where the salary of the employee is
between 10000 and 20000.
a. DDL (Data Definition Language): Used to define the data structure it consists of the
commands like CREATE, ALTER, DROP, etc.
b. DML (Data Manipulation language): Used to manipulate already existing data in the
database, commands like SELECT, UPDATE, INSERT
c. DCL (Data Control Language): Used to control access to data in the database, commands
like GRANT, REVOKE
CHAR is used to store fixed-length character strings, and VARCHAR2 used to store variable-
length character strings
By using the column alias in the ORDER BY instead of where clause for sorting
COALESCE() accepts two or more parameters, one can apply 2 or as many parameters but it
returns only the first non NULL parameter.
ISNULL() accepts only 2 parameters.
The first parameter is checked for a NULL value, if it is NULL then the 2nd parameter is
returned, otherwise, it returns the first parameter.
A trigger allows you to execute a batch of SQL code when an insert,update or delete command
is run against a specific table as Trigger is said to be the set of actions that are performed
whenever commands like insert, update or delete are given.
8. Write an SQL query to get the third maximum salary of an employee from
a table named employee_table.
SELECT TOP 1 salary FROM ( SELECT TOP 3 salary FROM employee_table ORDER BY
salary DESC ) AS emp ORDER BY salary ASC;
Aggregate functions are used to evaluate mathematical calculation and return single values.
This can be calculated from the columns in a table. Scalar functions return a single value based
on input value.
Example -. Aggregate – max(), count - Calculated with respect to numeric. Scalar – UCASE(),
NOW() – Calculated with respect to strings.
It is an unwanted situation where two or more transactions are waiting indefinitely for one
another to release the locks.
Left outer join is useful if you want all the records from the left table(first table) and only
matching records from 2nd table. The unmatched records are null records. Example: Left outer
join with "+" operator Select t1.col1,t2.col2….t ‘n’col ‘n.’. from table1 t1,table2 t2 where
t1.col=t2.col(+);
12. What is SQL injection?
The UNION operator combines the results of two or more Select statements by removing
duplicate rows. The columns and the data types must be the same in the SELECT statements.
SQL Constraints are used to specify the rules of data type in a table. They can be specified
while creating and altering the table. The following are the constraints in SQL: NOT NULL
CHECK DEFAULT UNIQUE PRIMARY KEY FOREIGN KEY
This command provides another name to a table or a column. It can be used in WHERE clause
of a SQL query using the "as" keyword.
Group functions work on a set of rows and return a single result per group. The popularly used
group functions are AVG, MAX, MIN, SUM, VARIANCE, COUNT
SELECT EmpNo, EmpName, Salary FROM employee WHERE deptNo in (select deptNo from
dept where deptName = ‘ECE’)
20. What are the main differences between #temp tables and @table
variables and which one is preferred ?
SQL clause is defined to limit the result set by providing condition to the query. This usually
filters some rows from the whole set of records. Example – Query that has WHERE condition
A stored procedure which calls by itself until it reaches some boundary condition. This recursive
function or procedure helps programmers to use the same set of code any number of times.
The Bulk Copy is a utility or a tool that exports/imports data from a table into a file and vice
versa.
In SQL cross join, a combination of every row from the two tables is included in the result set.
This is also called cross product set. For example, if table A has ten rows and table B has 20
rows, the result set will have 10 * 20 = 200 rows provided there is NOWHERE clause in the SQL
statement.
LIKE operator is used for pattern matching, and it can be used as- 1. % - Matches zero or more
characters. 2. _(Underscore) – Matching exactly one character.
SELECT CURDATE();
A query first takes the lowest level lock possible with the smallest row-level.When too many
rows are locked, the lock is escalated to a range or page lock. If too many pages are locked, it
may escalate to a table lock.
Order of SQL SELECT clauses is: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER
BY. Only the SELECT and FROM clauses are mandatory.
IN: Works on List result set Doesn’t work on subqueries resulting in Virtual tables with multiple
columns Compares every value in the result list.
Exists: Works on Virtual tables Is used with co-related queries Exits comparison when match is
found
34. How do you copy data from one table to another table ?
INSERT INTO table2 (column1, column2, column3, ...) SELECT column1, column2, column3, ...
FROM table1 WHERE condition;
35. List the ACID properties that makes sure that the database transactions
are processed
ACID (Atomicity, Consistency, Isolation, Durability) is a set of properties that guarantee that
database transactions are processed reliably.
36. What will be the output of the following Query, provided the employee
table has 10 records?
A stored procedure is a collection of SQL statements that can be used as a function to access
the database. We can create these stored procedures earlier before using it and can execute
them wherever required by applying some conditional logic to it. Stored procedures are also
used to reduce network traffic and improve performance.
This command is used to provide database access to users other than the administrator in SQL
privileges.
First Normal Form (1NF): It removes all duplicate columns from the table. It creates a table for
related data and identifies unique column values.
INSERT syntax is used to add a record in the table. INSERT into table_name VALUES (value1,
value2..);
1. MyISAM
2. Heap
3. Merge
4. INNO DB
5. ISAM
BLOB stands for large binary object. It is used to hold a variable amount of data. TEXT is a
case-insensitive BLOB. TEXT values are non-binary strings (character string).
45. How would you select all the users, whose phone number is NULL?
47. Write an SQL query to show the second highest salary from a table.
Select max(Salary) from Worker where Salary not in (Selct max(Salary) from Worker);
48. Write an SQL query to fetch three max salaries from a table.
SELECT distinct Salary from worker a WHERE 3 >= (SELECT count(distinct Salary) from
worker b WHERE a.salary <= b.Salary) order by a.Salary desc;
NOW () command is used to show current year,month,date with hours,minutes and seconds.
CURRENT_DATE() shows current year,month and date only.
UNIX_TIMESTAMP is the command which converts from MySQL timestamp to Unix timestamp
FROM_UNIXTIME is the command which converts from Unix timestamp to MySQL timestamp.
1. TINYTEXT
2. TEXT
3. MEDIUMTEXT
4. LONGTEXT
52. What is the group by clause used for?
The group by clause combines all those records that have identical values in a particular field or
any group of fields.
53. How do you get the last id without the max function?
54. Write a SQL query to fetch only even rows from the table.
Using the same Row_Number() and checking that the remainder when divided by 2 is 0-
SELECT E.EmpId, E.Project, E.Salary FROM ( SELECT *, Row_Number() OVER(ORDER BY
EmpId) AS RowNumber FROM EmployeeSalary ) E WHERE E.RowNumber % 2 = 0
55. Write a SQL query to create a new table with data and structure copied
from another table.
Case sensitivity: A and a are treated differently. Accent sensitivity: a and á are treated
differently. Kana sensitivity: Japanese kana characters Hiragana and Katakana are treated
differently. Width sensitivity: Same character represented in single-byte (half-width) and double-
byte (full-width) are treated differently.
In day to day activities the user needs to find out the data between some range. To achieve this
user needs to use Between..and operator or Greater than and less than operator.
Select * from Employee where salary >= 25000 and salary <= 50000;
58. How to calculate the number of rows in a table without using the count
function?
There are so many system tables which are very important .Using the system table user can
count the number of rows in the table.following query is helpful in that case, Select table_name,
num_rows from user_tables where table_name=’Employee’;
59. What is wrong with the following query? SELECT empName FROM
employee WHERE salary <> 6000
The following query will not fetch a record with the salary of 6000 but also will skip the record
with NULL.
60. Will the following statements execute? if yes what will be output?
SELECT NULL+1 SELECT NULL+'1'
Yes, no error. The output will be NULL. Perform any operation on NULL will get the NULL result.
Writes In SQL you can write In PL/SQL you can write block of
queries and command code that has procedures,
using DDL, DML functions, packages or variables,
statements. etc.
Use Using SQL, you can Using PL/SQL, you can create
retrieve, modify, add, applications or server pages that
delete, or manipulate the display the information obtained
data in the database. from SQL in a proper format.
Embed You can embed SQL You can not embed PL/SQL in
statement in PL/SQL. SQL
1 The WHERE clause specifies the criteria The HAVING clause cannot be
which individual records must meet to be used without the GROUP BY
selected by a query. It can be used clause
without the GROUP by clause
2 The WHERE clause selects rows before The HAVING clause selects rows
grouping after grouping
3 The WHERE clause cannot contain The HAVING clause can contain
aggregate functions aggregate functions
Helps to Process and Analyze the Data Using Helps to Add Business Logic
Simple Queries into an Application
Commercial Open-Source
MongoDB vs SQL
MongoDB MySQL
When you need high availability of If you're just starting and your database is not
data with automatic, fast, and going to scale much, MYSQL will help you in
instant data recovery easy and low-maintenance setup
If you have an unstable schema If you have fixed schema and data structure
and you want to reduce your isn't going to change over time like WikiPedia
schema migration cost
If most of the services are cloud- If data security is the topmost priority, MySQL
based, MongoDB is best suitable is most suited DBMS
for you
SQL server has stayed on top as one of the most popular database management products ever
since its first release in 1989 by Microsoft Corporation. The product is used across industries to
store and process large volumes of data. It was primarily built to store and process data that is
built on a relational model of data.
SQL Server is widely used for data analysis and also scaling up of data. SQL Server can be
used in conjunction with Big Data tools such as Hadoop.
SQL Server can be used to process data from various data sources such as Excel, Table, .Net
Framework application, etc.
1. Click on the below SQL Server official release link to access the latest version:
https://www.microsoft.com/en-in/sql-server/sql-server-downloads
2.Select the type of SQL Server edition that you want to install. SQL Server can be used on a
Cloud Platform or as an open-source edition(Express or Developer) in your local computer
system.
4.Save the .exe file on your system. Right-click on the .exe file and click on Open.
5.Click on ‘Yes’ to allow the changes to be made on your system and have SQL Server
Installed.
6.Once the installation is complete, restart your system, if required, and launch the SQL Server
Management Studio application from the START menu.
A Stored Procedure is nothing but a frequently used SQL query. Queries such as a SELECT
query, which would often be used to retrieve a set of information many times within a database,
can be saved as a Stored Procedure. The Stored Procedure, when called, executes the SQL
query save within the Stored Procedure.
Launch the SQL Server Management Studio application and from the Object Explorer window
pane, right-click on Databases and click on Restore. This would automatically restore the
database.
Launch the SQL Server Management Studio. Go to the Database for which you require the
Connection string. Right-click on the database and click on Properties. In the Properties window
that is displayed, you can view the Connection String property.
Connection strings help connect databases to another staging database or any external source
of data.
CTEs are Common Table Expressions that are used to create temporary result tables from
which data can be retrieved/ used. The standard syntax for a CTE with a SELECT statement is:
WITH RESULT AS
(SELECT COL1, COL2, COL3
FROM EMPLOYEE)
with result as
(select distinct salary, dense_rank() over (order by salary desc) as salary rank from employees)
(select distinct salary, dense_rank() over (order by salary desc) as salaryrank from employees)
In this way, CTEs can be used to find the nth highest salary within an organisation.
Launch your SQL Server Management Studio. Click on the Database connection for which you
want to change the login password. Click on Security from the options that get displayed.
Click on Logins and open your database connection. Type in the new password for login and
click on ‘OK’ to apply the changes.
FROM EMPLOYEE
GROUP BY COL1
In Windows 10, go to the START menu and locate the SQL Server.
You can run the below query to view the current version of SQL Server that you are using.
SELECT @@version;
From the Object Explorer window pane, go to the table where the column is present and choose
Design. Under the Column Name, select the name you want to rename and enter the new
name. Go to the File menu and click Save.
A Stored Procedure is nothing but a frequently used SQL query. Queries such as a SELECT
query, which would often be used to retrieve a set of information many times within a database,
can be saved as a Stored Procedure. The Stored Procedure, when called, executes the SQL
query save within the Stored Procedure.
You can execute the Stored Proc by using the command Exec Procedure_Name;
After installing the required version of SQL Server, it is easy to create new databases and
maintain them.
Indexes are database objects which help in retrieving records quickly and more efficiently.
Column indexes can be created on both Tables and Views. By declaring a Column as an index
within a table/ view, the user can access those records quickly by executing the index. Indexes
with more than one column are called Clustered indexes.
Syntax:
ON TABLE_NAME(COL1, COL2);
Tables are the fundamental storage objects within a database. A table is usually made up of
Rows and Columns. The below syntax can be used to create a new table with 3 columns.
COLUMN1 DATATYPE,
COLUMN2 DATATYPE,
COLUMN3 DATATYPE
);
Alternatively, you can right-click on Table in the Object Explorer window pane and select ‘New -
> Table’.
You can also define the type of Primary/ Foreign/ Check constraint when creating a table.
1. Launch the SQL Server Management Studio from the START menu.
2. In the dialog box shown below, select the Server Type as Database Engine and Server
Name as the name of your laptop/ desktop system.
3. Select the appropriate Authentication type and click on the Connect button.
4. A secure connection would be established, and the list of the available Databases will be
loaded in the Object Explorer window pane.
FROM EMPLOYEE
GROUP BY COL1
The Express and Developer versions (open-source versions) of the latest SQL Server release
can be downloaded from the official Microsoft website. The link is given below for reference.
https://www.microsoft.com/en-in/sql-server/sql-server-downloads
23. How to connect SQL Server management studio to the local database
1. Launch the SQL Server Management Studio from the START menu.
2. In the dialog box shown below, select the Server Type as Database Engine and Server
Name as the name of your laptop/ desktop system and click on the Connect button.
3. Select the Authentication as ‘Windows Authentication.
4. A secure connection would be established, and the list of the available Databases will be
loaded in the Object Explorer window pane.
From the Object Explorer window pane, go to the table in which the column is present and
choose Design. Under the Column Name, select the name you want to rename and enter the
new name. Go to the File menu and click Save.
1. Both the Express and Developer versions (free editions) of SQL Server can be
downloaded from the official Microsoft website. The link is given below for reference.
2. Click on the link below : https://www.microsoft.com/en-in/sql-server/sql-server-
downloads
3. Click on the search icon and type in - SQL Server 2014 download
4. Click on the result link to download and save SQL Server 2014.
From the START menu, type SQL Server. Right-click on the app and select uninstall to uninstall
the application from your system. Restart the system, if required, for the changes to get
affected.
Run the query SELECT @@version; to find the version and name of the SQL Server you are
using.
Case When statements in SQL are used to run through many conditions and to return a value
when one such condition is met. If none of the conditions is met in the When statements, then
the value mentioned in the Else statement is returned.
Syntax:
CASE
WHEN CONDITION1 THEN RESULT1
ELSE
RESULT
END;
Sample query:
select
sum (
case
else
end ) as Canada
from company_regions;
SUM (
CASE
ELSE
END
) AS "Mass",
SUM (
CASE
ELSE
END
) AS "Economic",
SUM (
CASE
ELSE
END
) AS " Luxury"
FROM
film;
Launch Google and in the Search toolbar, type in SQL Server Management Studio’ download.
Go to the routed website and click on the link to download. Once the download is complete,
open the .exe file to install the content of the file. Once the installation is complete, refresh or
restart the system, as required.
Alternatively, once SQL Server is installed and launched, it will prompt the user with an option to
launch SQ Server Management Studio.
A Stored Procedure is nothing but a frequently used SQL query. Queries such as a SELECT
query, which would often be used to retrieve a set of information many times within a database,
can be saved as a Stored Procedure. The Stored Procedure, when called, executes the SQL
query save within the Stored Procedure.
You can execute the Stored Proc by using the command Exec Procedure_Name;
Triggers in SQL Server are automatic functions that get executed AFTER or BEFORE an event
occurs.
For example: Trigger to update the employee’s salary to $40000 AFTER getting a promotion to
job level band D1. It is also referred to as a type of Stored Procedure. The type of trigger as
AFTER or BEFORE is defined in the syntax of the trigger itself.
The most common way of connecting to a SQL Server is using Windows Authentication.
Make sure to select the Server Name as the desktop or laptop system name.
Replication of a database node is the most common way to prevent the complete loss of any
data. When a database is replicated/ taken a copy of, it can be used across databases for data
reuse and synchronization. Apart from the primary motive of data backup, replicated data is also
used for data analysis in Big Data projects.
Click on the START menu and select All Programs. Select Microsoft SQL Server, select
Configuration Tools, and then select SQL Server Configuration tools. In that, select the SQL
Server Configuration Manager.
Collation refers to a set of pre-defined rules on SQL Server, which define the encoding rules of
character data both at a database and server level. Collation rules can be used on Metadata as
well.
SQL Server is used to retrieve and process various data that is built on a relational model.
Some of the common actions that can be taken on the data are CREATE, DELETE, INSERT,
UPDATE, SELECT, REVOKE, etc.
SQL Server can also be used to import and export data from different data sources. SQL Server
can also be connected to various other databases/ .Net framework using Connection Strings.
SQL Server can also be used in conjunction with Big Data tools like Hadoop.
Functions are pre-written codes that return a value and which help the user achieve a particular
task concerning viewing, manipulating, and processing data.
Examples of few functions are:
AGGREGATE FUNCTIONS:
COUNT()
STRING FUNCTIONS:
COALESCE()
CAST()
CONCAT()
SUBSTRING()
DATE FUNCTIONS:
GETDATE()
DATEADD()
DATEDIFF()
There are many types of functions such as Aggregate Functions, Date Functions, String
Functions, Mathematical functions, etc.
40. How to find nth highest salary in SQL Server without using a subquery
Query to find the 10 highest salary. For up-gradation of the b10 band.
with result as
(select distinct salary, dense_rank() over (order by salary desc) as salaryrank from employees)
(select distinct salary, dense_rank() over (order by salary desc) as salaryrank from employees)
select result.salary from result where result.salaryrank = 2
In this way, by replacing the salaryrank value, we can find the nth highest salary in any
organisation.
Temporary tables can be used to retain the structure and a subset of data from the original table
from which they were derived.
Syntax:
Temporary tables do not occupy any physical memory and can be used to retrieve data faster.
A schema is a logical visual representation of the database. It establishes and defines the
relationship between the various entities of a database. It describes the type of Constraints that
are applied to a database. It also explains the data types that are used. It can be used on
Tables and Views as well.
There are different types of schema. Some of the most popular ones are Star schema and
Snowflake schema. Star schema is the one that has the entities represented in a star shape,
and snowflake schema has its entities represented in a snowflake shape.
This brings us to the end of the SQL Interview questions. Glad to see you are now better
equipped to face an interview.
There are many sources online that can help you prepare for an SQL interview. You can go
through brief tutorials and free online courses on SQL (eg.: SQL basics on Great Learning
Academy) to revise your knowledge of SQL. You can also practice projects to help you with
practical aspects of the language. Lastly, there are many blogs such as this that list out all the
probable questions that an interviewer might ask.
SQL is a vast topic and there is a lot to learn. But the most basic skills that an SQL professional
should know are:
There are some platforms available online that can help you practice SQL such as SQL Fiddle,
SQLZOO, W3resource, Oracle LiveSQL, DB-Fiddle, Coding Groud, GitHub and others.
You can also refer to articles and blogs online that list the most important SQL interview
questions for preparation.
● CREATE DATABASE
● ALTER DATABASE
● CREATE TABLE
● ALTER TABLE
● DROP TABLE
● CREATE INDEX
● DROP INDEX
● CREATE DATABASE
● ALTER DATABASE
● CREATE TABLE
● ALTER TABLE
● DROP TABLE
● CREATE INDEX
● DROP INDEX
9. Is SQL coding?
Yes, SQL is a coding language/ programming language that falls under the category of domain-
specific programming language. It is used to access relational databases such as MySQL.
● SELECT
● INSERT
● UPDATE
● DELETE
● CREATE DATABASE
● ALTER DATABASE
SQL code is used to access and communicate with a database. It helps in performing tasks
such as updating and retrieving data from the databases.