SQL - Interview (1)
SQL - Interview (1)
SQL (Structured Query Language) is a domain-specific language used for managing and
manipulating relational databases. It allows you to create, read, update, and delete (CRUD
operations) data stored in relational database systems like MySQL, PostgreSQL, Oracle, SQL
Server, etc.
SQL is used to interact with databases to perform a variety of tasks, including querying data,
updating records, creating tables, and defining access controls.
Ans.
Basically, SQL is a command-based programming language but it doesn’t contain any control
flow statements.
Ans.
Both char and varchar are datatypes only, used for character strings. The only difference
between them is the length. Varchar is used for a variable length of strings and char is used for
a fixed length of strings. In char data type, if the length of the string is less than the fixed length
then it is padded with blank spaces to attain the fixed length. While varchar, padding won’t be
done.
Ans.
● LEFT JOIN: select column_name From table1 LEFT JOIN table2 on table1.column_name =
table2.column_name;
● RIGHT JOIN: select column_name From table1 RIGHT JOIN table2 on
table1.column_name = table2.column_name;
Ans. Consider two tables T1 and T2 having attributes like id, name.
● UNION ALL: select name from T1 UNION ALL select name from T2;
Ans.
DBMS is software that interacts with users, applications, and the database itself to capture and
analyze the data. It is a structured collection of data. There are two types of DBMS. They are:
● Relational DBMS: Data is stored in tables(relations). This involves the concept of tuples,
attributes.
● Non – Relational DBMS: In this, there won’t be any concept of tables, tuples, attributes.
Ans.
● OLAP: OLAP means Online Analytical Processing, it is an online query response system.
o Inner Join
o Right Join
o Left Join
o Self Join
Ans. Data organized in a model with Rows and Columns is called a table. Rows are horizontal
and Columns can be categorized as vertical. A table has a specified number of columns called
fields but can have an infinite number of rows which is called a record.
Ans.
Virtual memory is a memory management method that helps to execute the process using the
primary and secondary memory. Though the program gets executed using the main memory,
the resources and pages load from the secondary memory.
Ans.
FOREIGN KEY: This is a key used for linking 2 tables.
1. A FOREIGN KEY is a field or maybe a collection of fields in a table that corresponds to the
PRIMARY KEY of another table.
2. The table containing the FOREIGN KEY is called the CHILD TABLE and the table
containing the CANDIDATE KEY is called the PARENT TABLE.
Ques 11: What is the difference between DELETE and TRUNCATE statements?
Ans: DELETE:
● It is a DML command.
TRUNCATE:
● It is a DDL command.
Ans: The assurance of consistency and accuracy of the data over the entire life cycle is Data
Integrity. It is a critical aspect of the implementation, design, and usage of any system that
processes, stores 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.
Ans: SELECT is a SQL command that is used for selecting data from a database. The data which
is returned is saved in a result table, called the result-set.
Ans. Normalization is a way of organizing fields and tables of the database in a way that
reduces redundancy and dependency. The main objective is to create a single table where
operations like add, delete or modify can be performed on the field.
To ensure that the data transactions are processed reliably in a database system we use the
ACID property.
● Atomicity: It states that each transaction is all or nothing. It states that the entire
transaction fails if one part of the transaction fails and the database state is left
unchanged.
● Consistency: It ensures that the data must follow all validation rules. According to this a
transaction never leaves your database without its state being completed.
● Isolation: The main goal of providing isolation is concurrency control. This property
ensures that the concurrent property of execution should not be met.
● Durability: this property states that once a transaction has been committed, it remains
committed, whatever the situation be, even power loss, crashes, or errors.
Ans.
● Unique Index: It does not allow the field to possess redundant values if the column is
indexed uniquely. A unique index can be applied automatically if a primary key is
defined.
● Clustered Index: It rearranges the order of the table and searches based on key values.
Every table has only one clustered index.
● Non-Clustered Index: It causes no change in the order of the table and keeps a logical
order of the data intact. There can be many non-clustered indexes for a table.
Ques 17: What are the types of joins and explain each?
● Inner Join: Inner join returns rows when there is at least one match of rows between
the tables.
● Right Join: Right join return rows which are common between the tables and all rows of
the Right-hand side table. Simply, it returns all the rows from the right-hand side table
even though there are no matches in the left-hand side table.
● Left Join: Left join return rows which are common between the tables and all rows of
the Left-hand side table. Simply, it returns all the rows from the Left-hand side table
even though there are no matches in the Right-hand side table.
● Full Join: Full join return rows when there are matching rows in any one of the tables.
This means it returns all the rows from the left-hand side table and all the rows from the
right-hand side table.
Ans. A trigger is a special type of stored procedure that executes automatically in place or after
data changes. It allows executing a batch of code when an insert, update, or any other query is
executed against a specific table.
Ans.
Constraints are the limitations on the data type of a given table. A constraint can be specified
while creating or altering the table statement.
● NOT NULL.
● CHECK.
● DEFAULT.
● UNIQUE.
● PRIMARY KEY.
● FOREIGN KEY.
Ans.
SQL supports a set of operations that can be performed on the table data. These are used to get
meaningful results from data stored in the table, under different special conditions. The set
operators in SQL are :
● UNION.
● UNION ALL
● INTERSECT
● MINUS
Ans. The SQL DISTINCT keyword is used in conjunction with the SELECT statement to eliminate
all the duplicate records and fetch unique records.
Ans. A primary key also called a primary keyword, is a key in a relational database that is unique
for each record. This is a special kind of unique key, and it has an implicit, NOT NULL constraint.
It means Primary key values cannot be NULL. A relational database must always have one and
only one primary key.
Ans. A Unique key constraint uniquely identified each record in the database. This provides
uniqueness for the column or set of columns. A unique key is a set of one or more than one
field/column of a table that uniquely identifies a record in a database table. You can say that it
is a little like a primary key but it can accept only one null value and it cannot have duplicate
values.
Ans.
The normal forms can be divided into 4 forms, and they are explained below -.
● First Normal Form (1NF): According to this, remove all the redundant columns from a
table. Creation of tables for the related data and identification of unique columns.
● Second Normal Form (2NF): Should follow all requirements of the first normal form.
Arranging the data subsets in separate tables and Creation of relationships between the
tables using a primary key.
● Third Normal Form (3NF): Should follow all requirements of the 2NF. Removing the
columns which are not dependent on primary key constraints.
● BCNF (Boyce-Codd Normal Form): Meeting all the requirements of the third normal
form and it should not have multi-valued dependencies.
Ans. A query is a request for data. A DB query is a code written to get the information back
from the database. You ask the database for something and it answers in the best way it knows
with data as a result of a query.
Ques 26: What is a stored procedure? State the Advantages and Disadvantages of Stored
Procedure?
Ans. A stored procedure is a prepared SQL code that you can save, so the code can be reused
over and over again. Stored Procedure is a function that consists of many SQL statements to
access the database system. Stored procedure supports faster execution instead of executing
multiple queries. This reduces network traffic and provides better security to the data. The
disadvantage is that it can be executed only in the Database and uses more storage memory.
Ques 27: Write a SQL query to find the names of employees that begin with ‘A’?
Ans. To display the name of the employees that begin with ‘A’, type in the below command:
Ans. An alias is a SQL function that most, if not all, RDBMSs support. It’s a fictitious name given
to a table or table column for the purposes of a SQL query. Furthermore, aliasing can be used as
an obfuscation strategy to protect the true names of database fields. A correlation name is
another name for a table alias. The “AS” keyword represents an alias.
Ques 29: What is a User-defined function? What are its various types?
Ans. The user-defined functions in SQL are like functions in any other programming language
that accept parameters, perform complex calculations, and return a value. They are written to
use the logic repetitively whenever required. There are two types of SQL user-defined
functions:
● Scalar Function: As explained earlier, user-defined scalar functions return a single scalar
value.
Ans. SQL clause helps to limit the result set by providing a condition to the query. A clause helps
to filter the rows from the entire set of records.
Ques 31: What is the difference between ‘HAVING’ CLAUSE and a ‘WHERE’ CLAUSE?
Ans. HAVING clause can be used only with SELECT statement. It is usually used in a GROUP BY
clause and whenever GROUP BY is not used, HAVING behaves like a WHERE clause. Having
Clause is only used with the GROUP BY function in a query whereas WHERE Clause is applied to
each row before they are a part of the GROUP BY function in a query.
Ans. Creating empty tables with the same structure can be done smartly by fetching the
records of one table into a new table using the INTO operator while fixing a WHERE clause to be
false for all records. Hence, SQL prepares the new table with a duplicate structure to accept the
fetched records but since no records get fetched due to the WHERE clause in action, nothing is
inserted into the new table.
Ques 34: How to create empty tables with the same structure as another table?
Ans. Creating empty tables with the same structure can be done smartly by fetching the
records of one table into a new table using the INTO operator while fixing a WHERE clause to be
false for all records. Hence, SQL prepares the new table with a duplicate structure to accept the
fetched records but since no records get fetched due to the WHERE clause in action, nothing is
inserted into the new table.
Ques 35: What is the main difference between SQL and PL/SQL?
Ans. SQL is a query language that allows you to issue a single query or execute a single
insert/update/delete whereas PL/SQL is Oracle’s “Procedural Language” SQL, which allows you
to write a full program (loops, variables, etc.) to accomplish multiple operations such as
selects/inserts/updates/deletes.
Ans.
● Local variables: These variables can be used or exist only inside the function. These
variables are not used or referred to by any other function.
● Global variables: These variables are the variables that can be accessed throughout the
program. Global variables cannot be created whenever that function is called.
Ques 37: How can you fetch the first 5 characters of the string?
Ans.
A view is a virtual table that consists of a subset of data contained in a table. Since views are
not present, it takes less space to store. A view can have data of one or more tables combined
and it depends on the relationship.
Ques 40: What is the difference between SQL and NoSQL databases?
Ans. 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 the NoSQL database, we will be working with non-relational databases.
SQL (Structured Query Language) and MySQL are related but distinct concepts in database
management. Below is a breakdown of their differences:
1. Definition:
● SQL:
o It defines the structure and syntax used to query, insert, update, and delete
data.
o SQL is not a database system itself but a standardized language for managing
relational databases.
● MySQL:
o MySQL allows users to create and manage databases, and execute SQL queries
on the data.
2. Purpose:
● SQL:
o SQL is designed for interacting with relational databases and defining database
structures (tables, views, etc.).
● MySQL:
o MySQL is a system that manages databases and provides tools to interact with
them.
o It allows users to store data, execute SQL queries, and maintain databases in a
multi-user environment.
3. Usage:
● SQL:
o SQL is used to query and manipulate data within any database that supports
the SQL language (like MySQL, PostgreSQL, Oracle, etc.).
● MySQL:
o MySQL is the software or service that actually executes SQL queries on the
database, stores the data, and maintains the structure.
● SQL:
o SQL is standardized and works with any relational database that supports the
language (including MySQL, PostgreSQL, Microsoft SQL Server, Oracle, etc.).
o There may be slight variations in SQL syntax and features depending on the
RDBMS.
● MySQL:
● Aggregate functions perform calculations on sets of data and return a single result,
often used with the GROUP BY clause.
● Scalar functions operate on individual data points within a row and return a result for
each row, allowing data transformation and manipulation.
To optimize subqueries:
OLTP, or Online Transaction Processing, is a type of database system designed for handling a
large volume of real-time, short, and frequent transactions. It’s commonly used in applications
like e-commerce, banking, and inventory management to process day-to-day operations
efficiently. OLTP systems focus on maintaining data integrity and fast transaction processing.
Ques 46: What is composite key?
Ans.
OrderNumber INT,
LineItemNumber INT,
ProductID INT,
Quantity INT,
);
Optimization techniques for OLAP (Online Analytical Processing) systems include aggregating
data, partitioning, indexing, using materialized views, caching, parallel processing,
compression, and hardware acceleration. These methods aim to speed up query execution
and enhance data analysis performance in OLAP environments.
Indexing in a database creates a separate structure (like a B-tree) that stores a sorted version
of certain columns, allowing for faster data retrieval. It speeds up queries but requires
maintenance and careful selection of indexed columns for optimal performance
Ques 50: What is Cursor? How to use a Cursor?
Ans.
A cursor in databases is a pointer used to iterate through the rows of a result set. To use a
cursor:
3. Fetch: Retrieve rows one by one from the result set using FETCH.
Cursors are typically used for row-by-row data manipulation and are supported in SQL-based
database systems like SQL Server, Oracle, and PostgreSQL.