SQL Interview Questions:
[Link] is Data?
Any sort of information that is stored is called data.
Examples:
.Messages & multimedia on WhatsApp
.Products and orders on Amazon
.Contact details in telephone directory, etc.
[Link] is Database?
An organised collection of data is called a database.
3. What is RDBMS? How is it different from DBMS?
RDBMS stands for Relational Database Management System. The key difference here,
compared to DBMS, is that RDBMS stores data in the form of a collection of tables,
and relations can be defined between the common fields of these tables. Most modern
database management systems like MySQL, Microsoft SQL Server, Oracle, IBM DB2, and
Amazon Redshift are based on RDBMS.
[Link] is Database Management System(DBMS)?
A software that is used to easily store and access data from the database in a
secure way.
[Link] are the advantages of DBMS?
Advantages
a) Security: Data is stored & maintained securely.
b) Ease of Use: Provides simpler ways to create & update data at the rate it
is generated and updated respectively.
c) Durability and Availability: Durable and provides access to all the
clients at any point in time.
d) Performance: Quickly accessible to all the clients(applications and
stakeholders).
[Link] is SQL?
SQL stands for Structured Query Language. It is the standard language for
relational database management systems. It is especially useful in handling
organized data comprised of entities (variables) and relations between different
entities of the data.
[Link] is the difference between SQL and MySQL?
SQL is a standard language for retrieving and manipulating structured databases. On
the contrary, MySQL is a relational database management system, like SQL Server,
Oracle or IBM DB2, that is used to manage SQL databases.
[Link] are Tables and Fields?
A table is an organized collection of data stored in the form of rows and columns.
Columns can be categorized as vertical and rows as horizontal. The columns in a
table are called fields while the rows can be referred to as records.
[Link] are Constraints in SQL?
Constraints are used to specify the rules concerning data in the table. It can be
applied for single or multiple fields in an SQL table during the creation of the
table or after creating using the ALTER TABLE command. The constraints are:
NOT NULL - Restricts NULL value from being inserted into a column.
CHECK - Verifies that all values in a field satisfy a condition.
DEFAULT - Automatically assigns a default value if no value has been specified for
the field.
UNIQUE - Ensures unique values to be inserted into the field.
INDEX - Indexes a field providing faster retrieval of records.
PRIMARY KEY - Uniquely identifies each record in a table.
FOREIGN KEY - Ensures referential integrity for a record in another table.
[Link] is a Primary Key?
The PRIMARY KEY constraint uniquely identifies each row in a table. It must contain
UNIQUE values and has an implicit NOT NULL constraint.
A table in SQL is strictly restricted to have one and only one primary key, which
is comprised of single or multiple fields (columns).
CREATE TABLE Students ( /* Create table with a single field as primary key */
ID INT NOT NULL
Name VARCHAR(255)
PRIMARY KEY (ID)
);
CREATE TABLE Students ( /* Create table with multiple fields as primary key */
ID INT NOT NULL
LastName VARCHAR(255)
FirstName VARCHAR(255) NOT NULL,
CONSTRAINT PK_Student
PRIMARY KEY (ID, FirstName)
);
ALTER TABLE Students /* Set a column as primary key */
ADD PRIMARY KEY (ID);
ALTER TABLE Students /* Set multiple columns as primary key */
ADD CONSTRAINT PK_Student /*Naming a Primary Key*/
PRIMARY KEY (ID, FirstName);
11. What is a UNIQUE constraint?
A UNIQUE constraint ensures that all values in a column are different. This
provides uniqueness for the column(s) and helps identify each row uniquely. Unlike
primary key, there can be multiple unique constraints defined per table. The code
syntax for UNIQUE is quite similar to that of PRIMARY KEY and can be used
interchangeably.
CREATE TABLE Students ( /* Create table with a single field as unique */
ID INT NOT NULL UNIQUE
Name VARCHAR(255)
);
CREATE TABLE Students ( /* Create table with multiple fields as unique */
ID INT NOT NULL
LastName VARCHAR(255)
FirstName VARCHAR(255) NOT NULL
CONSTRAINT PK_Student
UNIQUE (ID, FirstName)
);
ALTER TABLE Students /* Set a column as unique */
ADD UNIQUE (ID);
ALTER TABLE Students /* Set multiple columns as unique */
ADD CONSTRAINT PK_Student /* Naming a unique constraint */
UNIQUE (ID, FirstName);
12. What is a Foreign Key?
A FOREIGN KEY comprises of single or collection of fields in a table that
essentially refers to the PRIMARY KEY in another table. Foreign key constraint
ensures referential integrity in the relation between two tables.
The table with the foreign key constraint is labeled as the child table, and the
table containing the candidate key is labeled as the referenced or parent table.
CREATE TABLE Students ( /* Create table with foreign key - Way 1 */
ID INT NOT NULL
Name VARCHAR(255)
LibraryID INT
PRIMARY KEY (ID)
FOREIGN KEY (Library_ID) REFERENCES Library(LibraryID)
);
CREATE TABLE Students ( /* Create table with foreign key - Way 2 */
ID INT NOT NULL PRIMARY KEY
Name VARCHAR(255)
LibraryID INT FOREIGN KEY (Library_ID) REFERENCES Library(LibraryID)
);
ALTER TABLE Students /* Add a new foreign key */
ADD FOREIGN KEY (LibraryID)
REFERENCES Library (LibraryID);
13. What is a Join? List its different types.
The SQL Join clause is used to combine records (rows) from two or more tables in a
SQL database based on a related column between the two.
There are four different types of JOINs in SQL:
(INNER) JOIN: Retrieves records that have matching values in both tables involved
in the join. This is the widely used join for queries.
SELECT *
FROM Table_A
JOIN Table_B;
SELECT *
FROM Table_A
INNER JOIN Table_B;
LEFT (OUTER) JOIN: Retrieves all the records/rows from the left and the matched
records/rows from the right table.
SELECT *
FROM Table_A A
LEFT JOIN Table_B B
ON [Link] = [Link];
RIGHT (OUTER) JOIN: Retrieves all the records/rows from the right and the matched
records/rows from the left table.
SELECT *
FROM Table_A A
RIGHT JOIN Table_B B
ON [Link] = [Link];
FULL (OUTER) JOIN: Retrieves all the records where there is a match in either the
left or right table.
SELECT *
FROM Table_A A
FULL JOIN Table_B B
ON [Link] = [Link];
14. What is a Self-Join?
A self JOIN is a case of regular join where a table is joined to itself based on
some relation between its own column(s). Self-join uses the INNER JOIN or LEFT JOIN
clause and a table alias is used to assign different names to the table within the
query.
SELECT A.emp_id AS "Emp_ID",A.emp_name AS "Employee",
B.emp_id AS "Sup_ID",B.emp_name AS "Supervisor"
FROM employee A, employee B
WHERE A.emp_sup = B.emp_id;
15. What is a Cross-Join?
Cross join can be defined as a cartesian product of the two tables included in the
join. The table after join contains the same number of rows as in the cross-product
of the number of rows in the two tables. If a WHERE clause is used in cross join
then the query will work like an INNER JOIN.
SELECT [Link], [Link]
FROM students AS stu
CROSS JOIN subjects AS sub;
16. What is an Index? Explain its different types.
A database index is a data structure that provides a quick lookup of data in a
column or columns of a table. It enhances the speed of operations accessing data
from a database table at the cost of additional writes and memory to maintain the
index data structure.
CREATE INDEX index_name /* Create Index */
ON table_name (column_1, column_2);
DROP INDEX index_name; /* Drop Index */
There are different types of indexes that can be created for different purposes:
Unique and Non-Unique Index:
Unique indexes are indexes that help maintain data integrity by ensuring that no
two rows of data in a table have identical key values. Once a unique index has been
defined for a table, uniqueness is enforced whenever keys are added or changed
within the index.
CREATE UNIQUE INDEX myIndex
ON students (enroll_no);
Non-unique indexes, on the other hand, are not used to enforce constraints on the
tables with which they are associated. Instead, non-unique indexes are used solely
to improve query performance by maintaining a sorted order of data values that are
used frequently.
Clustered and Non-Clustered Index:
Clustered indexes are indexes whose order of the rows in the database corresponds
to the order of the rows in the index. This is why only one clustered index can
exist in a given table, whereas, multiple non-clustered indexes can exist in the
table.
The only difference between clustered and non-clustered indexes is that the
database manager attempts to keep the data in the database in the same order as the
corresponding keys appear in the clustered index.
Clustering indexes can improve the performance of most query operations because
they provide a linear-access path to data stored in the database.
[Link] is the difference between Clustered and Non-clustered index?
As explained above, the differences can be broken down into three small factors -
Clustered index modifies the way records are stored in a database based on the
indexed column. A non-clustered index creates a separate entity within the table
which references the original table.
Clustered index is used for easy and speedy retrieval of data from the database,
whereas, fetching records from the non-clustered index is relatively slower.
In SQL, a table can have a single clustered index whereas it can have multiple non-
clustered indexes.
[Link] is Data Integrity?
Data Integrity is the assurance of accuracy and consistency of data over its entire
life-cycle and is a critical aspect of 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.
19. What is a Query?
A query is a request for data or information from a database table or combination
of tables. A database query can be either a select query or an action query.
SELECT fname, lname /* select query */
FROM [Link]
WHERE student_id = 1;
UPDATE [Link] /* action query */
SET fname = 'Captain', lname = 'America'
WHERE student_id = 1;
20. What is a Subquery? What are its types?
A subquery is a query within another query, also known as a nested query or inner
query. It is used to restrict or enhance the data to be queried by the main query,
thus restricting or enhancing the output of the main query respectively. For
example, here we fetch the contact information for students who have enrolled for
the maths subject:
SELECT name, email, mob, address
FROM [Link]
WHERE roll_no IN (
SELECT roll_no
FROM [Link]
WHERE subject = 'Maths');
There are two types of subquery - Correlated and Non-Correlated.
A correlated subquery cannot be considered as an independent query, but it can
refer to the column in a table listed in the FROM of the main query.
A non-correlated subquery can be considered as an independent query and the output
of the subquery is substituted in the main query.
Write a SQL query to update the field "status" in table "applications" from 0 to 1.
Write a SQL query to select the field "app_id" in table "applications" where
"app_id" less than 1000.
Write a SQL query to fetch the field "app_name" from "apps" where "[Link]" is
equal to the above collection of "app_id".
19. What is the SELECT statement?
SELECT operator in SQL is used to select data from a database. The data returned is
stored in a result table, called the result-set.
SELECT * FROM [Link];
21. What are some common clauses used with SELECT query in SQL?
Some common SQL clauses used in conjuction with a SELECT query are as follows:
WHERE clause in SQL is used to filter records that are necessary, based on specific
conditions.
ORDER BY clause in SQL is used to sort the records based on some field(s) in
ascending (ASC) or descending order (DESC).
SELECT *
FROM [Link]
WHERE graduation_year = 2019
ORDER BY studentID DESC;
GROUP BY clause in SQL is used to group records with identical data and can be used
in conjunction with some aggregation functions to produce summarized results from
the database.
HAVING clause in SQL is used to filter records in combination with the GROUP BY
clause. It is different from WHERE, since the WHERE clause cannot filter aggregated
records.
SELECT COUNT(studentId), country
FROM [Link]
WHERE country != "INDIA"
GROUP BY country
HAVING COUNT(studentID) > 5;
22. What are UNION, MINUS and INTERSECT commands?
The UNION operator combines and returns the result-set retrieved by two or more
SELECT statements.
The MINUS operator in SQL is used to remove duplicates from the result-set obtained
by the second SELECT query from the result-set obtained by the first SELECT query
and then return the filtered results from the first.
The INTERSECT clause in SQL combines the result-set fetched by the two SELECT
statements where records from one match the other and then returns this
intersection of result-sets.
Certain conditions need to be met before executing either of the above statements
in SQL -
Each SELECT statement within the clause must have the same number of columns
The columns must also have similar data types
The columns in each SELECT statement should necessarily have the same order
SELECT name FROM Students /* Fetch the union of queries */
UNION
SELECT name FROM Contacts;
SELECT name FROM Students /* Fetch the union of queries with duplicates*/
UNION ALL
SELECT name FROM Contacts;
SELECT name FROM Students /* Fetch names from students */
MINUS /* that aren't present in contacts */
SELECT name FROM Contacts;
SELECT name FROM Students /* Fetch names from students */
INTERSECT /* that are present in contacts as well */
SELECT name FROM Contacts;
[Link] is Cursor? How to use a Cursor?
A database cursor is a control structure that allows for the traversal of records
in a database. Cursors, in addition, facilitates processing after traversal, such
as retrieval, addition, and deletion of database records. They can be viewed as a
pointer to one row in a set of rows.
Working with SQL Cursor:
DECLARE a cursor after any variable declaration. The cursor declaration must always
be associated with a SELECT Statement.
Open cursor to initialize the result set. The OPEN statement must be called before
fetching rows from the result set.
FETCH statement to retrieve and move to the next row in the result set.
Call the CLOSE statement to deactivate the cursor.
Finally use the DEALLOCATE statement to delete the cursor definition and release
the associated resources.
[Link] are Entities and Relationships?
Entity: An entity can be a real-world object, either tangible or intangible, that
can be easily identifiable. For example, in a college database, students,
professors, workers, departments, and projects can be referred to as entities. Each
entity has some associated properties that provide it an identity.
Relationships: Relations or links between entities that have something to do with
each other. For example - The employee's table in a company's database can be
associated with the salary table in the same database.
[Link] the different types of relationships in SQL.
a)One-to-One - This can be defined as the relationship between two tables
where each record in one table is associated with the maximum of one record in the
other table.
b)One-to-Many & Many-to-One - This is the most commonly used relationship
where a record in a table is associated with multiple records in the other table.
c)Many-to-Many - This is used in cases when multiple instances on both sides
are needed for defining a relationship.
d)Self-Referencing Relationships - This is used when a table needs to define
a relationship with itself.
[Link] is an Alias in SQL?
An alias is a feature of SQL that is supported by most, if not all, RDBMSs. It is a
temporary name assigned to the table or table column for the purpose of a
particular SQL query. In addition, aliasing can be employed as an obfuscation
technique to secure the real names of database fields. A table alias is also called
a correlation name.
An alias is represented explicitly by the AS keyword but in some cases, the same
can be performed without it as well. Nevertheless, using the AS keyword is always a
good practice.
SELECT A.emp_name AS "Employee" /* Alias using AS keyword */
B.emp_name AS "Supervisor"
FROM employee A, employee B /* Alias without AS keyword */
WHERE A.emp_sup = B.emp_id;
[Link] is a View?
A view in SQL is a virtual table based on the result-set of an SQL statement. 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.
[Link] is Normalization?
Normalization represents the way of organizing structured data in the database
efficiently. It includes the creation of tables, establishing relationships between
them, and defining rules for those relationships. Inconsistency and redundancy can
be kept in check based on these rules, hence, adding flexibility to the database.
29. What is Denormalization?
Denormalization is the inverse process of normalization, where the normalized
schema is converted into a schema that has redundant information. The performance
is improved by using redundancy and keeping the redundant data consistent. The
reason for performing denormalization is the overheads produced in the query
processor by an over-normalized structure.
[Link] are the TRUNCATE, DELETE and DROP statements?
DELETE statement is used to delete rows from a table.
DELETE FROM Candidates
WHERE CandidateId > 1000;
TRUNCATE command is used to delete all the rows from the table and free the space
containing the table.
TRUNCATE TABLE Candidates;
DROP command is used to remove an object from the database. If you drop a table,
all the rows in the table are deleted and the table structure is removed from the
database.
DROP TABLE Candidates;
31. What is the difference between DROP and TRUNCATE statements?
If a table is dropped, all things associated with the tables are dropped as well.
This includes - the relationships defined on the table with other tables, the
integrity checks and constraints, access privileges and other grants that the table
has. To create and use the table again in its original form, all these relations,
checks, constraints, privileges and relationships need to be redefined. However, if
a table is truncated, none of the above problems exist and the table retains its
original structure.
32. What is the difference between DELETE and TRUNCATE statements?
The TRUNCATE command is used to delete all the rows from the table and free the
space containing the table.
The DELETE command deletes only the rows from the table based on the condition
given in the where clause or deletes all the rows from the table if no condition is
specified. But it does not free the space containing the table.
33. What are Aggregate and Scalar functions?
An aggregate function performs operations on a collection of values to return a
single scalar value. Aggregate functions are often used with the GROUP BY and
HAVING clauses of the SELECT statement. Following are the widely used SQL aggregate
functions:
AVG() - Calculates the mean of a collection of values.
COUNT() - Counts the total number of records in a specific table or view.
MIN() - Calculates the minimum of a collection of values.
MAX() - Calculates the maximum of a collection of values.
SUM() - Calculates the sum of a collection of values.
FIRST() - Fetches the first element in a collection of values.
LAST() - Fetches the last element in a collection of values.
Note: All aggregate functions described above ignore NULL values except for the
COUNT function.
A scalar function returns a single value based on the input value. Following are
the widely used SQL scalar functions:
LEN() - Calculates the total length of the given field (column).
UCASE() - Converts a collection of string values to uppercase characters.
LCASE() - Converts a collection of string values to lowercase characters.
MID() - Extracts substrings from a collection of string values in a table.
CONCAT() - Concatenates two or more strings.
RAND() - Generates a random collection of numbers of a given length.
ROUND() - Calculates the round-off integer value for a numeric field (or decimal
point values).
NOW() - Returns the current date & time.
FORMAT() - Sets the format to display a collection of values.
34. What is User-defined function? What are its various types?
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.
Table-Valued Functions: User-defined table-valued functions return a table as
output.
Inline: returns a table data type based on a single SELECT statement.
Multi-statement: returns a tabular result-set but, unlike inline, multiple SELECT
statements can be used inside the function body.
35. What is OLTP?
OLTP stands for Online Transaction Processing, 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. To avoid single points of
failure, OLTP systems are often decentralized. These systems are usually designed
for a large number of users who conduct short transactions. Database queries are
usually simple, require sub-second response times, and return relatively few
records. Here is an insight into the working of an OLTP system [ Note - The figure
is not important for interviews ]
36. What are the differences between OLTP and OLAP?
OLTP stands for Online Transaction Processing, is a class of software applications
capable of supporting transaction-oriented programs. An important attribute of an
OLTP system is its ability to maintain concurrency. OLTP systems often follow a
decentralized architecture to avoid single points of failure. These systems are
generally designed for a large audience of end-users who conduct short
transactions. Queries involved in such databases are generally simple, need fast
response times, and return relatively few records. A number of transactions per
second acts as an effective measure for such systems.
OLAP stands for Online Analytical Processing, a class of software programs that are
characterized by the relatively low frequency of online transactions. Queries are
often too complex and involve a bunch of aggregations. For OLAP systems, the
effectiveness measure relies highly on response time. Such systems are widely used
for data mining or maintaining aggregated, historical data, usually in multi-
dimensional schemas.
[Link] is Collation? What are the different types of Collation Sensitivity?
Collation refers to a set of rules that determine how data is sorted and compared.
Rules defining the correct character sequence are used to sort the character data.
It incorporates options for specifying case sensitivity, accent marks, kana
character types, and character width. Below are the different types of collation
sensitivity:
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.
38. What is a Stored Procedure?
A stored procedure is a subroutine available to applications that access a
relational database management system (RDBMS). Such procedures are stored in the
database data dictionary. The sole disadvantage of stored procedure is that it can
be executed nowhere except in the database and occupies more memory in the database
server. It also provides a sense of security and functionality as users who can't
access the data directly can be granted access via stored procedures.
DELIMITER $$
CREATE PROCEDURE FetchAllStudents()
BEGIN
SELECT * FROM [Link];
END $$
DELIMITER ;
[Link] is a Recursive Stored Procedure?
A stored procedure that calls itself until a boundary condition is reached, is
called a recursive stored procedure. This recursive function helps the programmers
to deploy the same set of code several times as and when required. Some SQL
programming languages limit the recursion depth to prevent an infinite loop of
procedure calls from causing a stack overflow, which slows down the system and may
lead to system crashes.
DELIMITER $$ /* Set a new delimiter => $$ */
CREATE PROCEDURE calctotal( /* Create the procedure */
IN number INT, /* Set Input and Ouput variables */
OUT total INT
) BEGIN
DECLARE score INT DEFAULT NULL; /* Set the default value => "score" */
SELECT awards FROM achievements /* Update "score" via SELECT query */
WHERE id = number INTO score;
IF score IS NULL THEN SET total = 0; /* Termination condition */
ELSE
CALL calctotal(number+1); /* Recursive call */
SET total = total + score; /* Action after recursion */
END IF;
END $$ /* End of procedure */
DELIMITER ; /* Reset the delimiter */
40. How to create empty tables with the same structure as another table?
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.
SELECT * INTO Students_copy
FROM Students WHERE 1 = 2;
41. What is Pattern Matching in SQL?
SQL pattern matching provides for pattern search in data if you have no clue as to
what that word should be. This kind of SQL query uses wildcards to match a string
pattern, rather than writing the exact word. The LIKE operator is used in
conjunction with SQL Wildcards to fetch the required information.
Using the % wildcard to perform a simple search
The % wildcard matches zero or more characters of any type and can be used to
define wildcards both before and after the pattern. Search a student in your
database with first name beginning with the letter K:
SELECT *
FROM students
WHERE first_name LIKE 'K%'
Omitting the patterns using the NOT keyword
Use the NOT keyword to select records that don't match the pattern. This query
returns all students whose first name does not begin with K.
SELECT *
FROM students
WHERE first_name NOT LIKE 'K%'
Matching a pattern anywhere using the % wildcard twice
Search for a student in the database where he/she has a K in his/her first name.
SELECT *
FROM students
WHERE first_name LIKE '%Q%'
Using the _ wildcard to match pattern at a specific position
The _ wildcard matches exactly one character of any type. It can be used in
conjunction with % wildcard. This query fetches all students with letter K at the
third position in their first name.
SELECT *
FROM students
WHERE first_name LIKE '__K%'
Matching patterns for a specific length
The _ wildcard plays an important role as a limitation when it matches exactly one
character. It limits the length and position of the matched results. For example -
SELECT * /* Matches first names with three or more letters */
FROM students
WHERE first_name LIKE '___%'
SELECT * /* Matches first names with exactly four characters */
FROM students
WHERE first_name LIKE '____'
[Link] SQL support programming language features?
It is true that SQL is a language, but it does not support programming as it is not
a programming language, it is a command language. We do not have conditional
statements in SQL like for loops or if..else, we only have commands which we can
use to query, update, delete, etc. data in the database. SQL allows us to
manipulate data in a database.
[Link] is the difference between BETWEEN and IN operators in SQL?
BETWEEN: The BETWEEN operator is used to fetch rows based on a range of values.
For example,
SELECT * FROM Students
WHERE ROLL_NO BETWEEN 20 AND 30;
This query will select all those rows from the table. Students where the value of
the field ROLL_NO lies between 20 and 30.
IN: The IN operator is used to check for values contained in specific sets.
For example,
SELECT * FROM Students
WHERE ROLL_NO IN (20,21,23);
This query will select all those rows from the table Students where the value of
the field ROLL_NO is either 20 or 21 or 23.
[Link] is the difference between CHAR and VARCHAR2 datatype in SQL?
Both of these data types are used for characters, but varchar2 is used for
character strings of variable length, whereas char is used for character strings of
fixed length. For example, if we specify the type as char(5) then we will not be
allowed to store a string of any other length in this variable, but if we specify
the type of this variable as varchar2(5) then we will be allowed to store strings
of variable length. We can store a string of length 3 or 4 or 2 in this variable.
45. Name different types of case manipulation functions available in SQL.
There are three types of case manipulation functions available in SQL. They are,
LOWER: The purpose of this function is to return the string in lowercase. It takes
a string as an argument and returns the string by converting it into lower case.
Syntax:
LOWER(‘string’)
UPPER: The purpose of this function is to return the string in uppercase. It takes
a string as an argument and returns the string by converting it into uppercase.
Syntax:
UPPER(‘string’)
INITCAP: The purpose of this function is to return the string with the first letter
in uppercase and the rest of the letters in lowercase.
Syntax:
INITCAP(‘string’)
[Link] do you mean by data definition language?
Data definition language or DDL allows to execution of queries like CREATE, DROP,
and ALTER. That is those queries that define the data.
47. What do you mean by data manipulation language?
Data manipulation Language or DML is used to access or manipulate data in the
database.
It allows us to perform the below-listed functions:
Insert data or rows in a database
Delete data from the database
Retrieve or fetch data
Update data in a database.
11. What is the difference between primary key and unique constraints?
The primary key cannot have NULL values, the unique constraints can have NULL
values. There is only one primary key in a table, but there can be multiple unique
constraints. The primary key creates the clustered index automatically but the
unique key does not.
[Link] is a join in SQL? What are the types of joins?
An SQL Join statement is used to combine data or rows from two or more tables based
on a common field between them. Different types of Joins are:
INNER JOIN: The INNER JOIN keyword selects all rows from both tables as long as the
condition is satisfied. This keyword will create the result set by combining all
rows from both the tables where the condition satisfies i.e. the value of the
common field will be the same.
LEFT JOIN: This join returns all the rows of the table on the left side of the join
and matching rows for the table on the right side of the join. For the rows for
which there is no matching row on the right side, the result set will be null. LEFT
JOIN is also known as LEFT OUTER JOIN
RIGHT JOIN: RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of
the table on the right side of the join and matching rows for the table on the left
side of the join. For the rows for which there is no matching row on the left side,
the result set will contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN.
FULL JOIN: FULL JOIN creates the result set by combining the results of both LEFT
JOIN and RIGHT JOIN. The result set will contain all the rows from both tables. For
the rows for which there is no matching, the result set will contain NULL values.
49. What is an index?
A database index is a data structure that improves the speed of data retrieval
operations on a database table at the cost of additional writes and the use of more
storage space to maintain the extra copy of data. Data can be stored only in one
order on a disk. To support faster access according to different values, a faster
search like a binary search for different values is desired. For this purpose,
indexes are created on tables. These indexes need extra space on the disk, but they
allow faster search according to different frequently searched values.
50. What are table and Field?
Table: A table has a combination of rows and columns. Rows are called records and
columns are called fields. In MS SQL Server, the tables are being designated within
the database and schema names.
[Link] WITH clause in SQL?
The WITH clause provides a way relationship of defining a temporary relationship
whose definition is available only to the query in which the with clause occurs.
SQL applies predicates in the WITH clause after groups have been formed, so
aggregate functions may be used.
52. What are all the different attributes of indexes?
The indexing has various attributes:
Access Types: This refers to the type of access such as value-based search, range
access, etc.
Access Time: It refers to the time needed to find a particular data element or set
of elements.
Insertion Time: It refers to the time taken to find the appropriate space and
insert new data.
Deletion Time: Time is taken to find an item and delete it as well as update the
index structure.
Space Overhead: It refers to the additional space required by the index.
53. What is a Cursor?
The cursor is a Temporary Memory or Temporary Work Station. It is Allocated by
Database Server at the Time of Performing DML operations on the Table by the User.
Cursors are used to store Database Tables.
[Link] is a query?
An SQL query is used to retrieve the required data from the database. However,
there may be multiple SQL queries that yield the same results but with different
levels of efficiency. An inefficient query can drain the database resources, reduce
the database speed or result in a loss of service for other users. So it is very
important to optimize the query to obtain the best database performance.
55. What is a subquery?
In SQL a Subquery can be simply defined as a query within another query. In other
words, we can say that a Subquery is a query that is embedded in the WHERE clause
of another SQL query.
56. What are the different operators available in SQL?
There are three operators available in SQL namely:
Arithmetic Operators
Logical Operators
Comparison Operators
57. What is a trigger?
The trigger is a statement that a system executes automatically when there is any
modification to the database. In a trigger, we first specify when the trigger is to
be executed and then the action to be performed when the trigger executes. Triggers
are used to specify certain integrity constraints and referential constraints that
cannot be specified using the constraint mechanism of SQL.
[Link] is the difference between SQL DELETE and SQL TRUNCATE commands?
SQL DELETE
SQL TRUNCATE
The DELETE statement removes rows one at a time and records an entry in the
transaction log for each deleted row. i)TRUNCATE TABLE removes the data by
deallocating the
data pages used to store the table data and records
only the
page deallocations in the transaction log.
DELETE command is slower than the identityTRUNCATE command.
ii)While the TRUNCATE command is faster than the
DELETE
command.
To use Delete you need DELETE permission on the table.
iii)To use Truncate on a table we need at least ALTER
permission on the table.
The identity of the column retains the identity after using DELETE Statement on the
table. iv)The identity of the column is reset to its seed
value
if the table contains an identity column.
The delete can be used with indexed views.
v)Truncate cannot be used with indexed views.
[Link] are local and global variables and their differences?
Global Variable:
In contrast, global variables are variables that are defined outside of functions.
These variables have global scope, so they can be used by any function without
passing them to the function as parameters.
Local Variable:
Local variables are variables that are defined within functions. They have local
scope, which means that they can only be used within the functions that define
them.
[Link] the function which is used to remove spaces at the end of a string?
In SQL the spaces at the end of the string are removed by a trim function.
Syntax:
Trim(s) Where s is a any string.
[Link] is the difference between TRUNCATE and DROP statements?
SQL DROP TRUNCATE
The DROP command is used to remove the table definition and its contents.
Whereas the TRUNCATE command is used to delete all the rows from the table.
In the DROP command, table space is freed from memory. While
the TRUNCATE command does not free the table space from memory.
DROP is a DDL(Data Definition Language) command. Whereas the
TRUNCATE is also a DDL(Data Definition Language) command.
In the DROP command, a view of the table does not exist. While in
this command, a view of the table exists.
In the DROP command, integrity constraints will be removed. While in
this command, integrity constraints will not be removed.
In the DROP command, undo space is not used. While in
this command, undo space is used but less than DELETE.
The DROP command is quick to perform but gives rise to complications. While
this command is faster than DROP.
[Link] are aggregate and scalar functions?
For doing operations on data SQL has many built-in functions, they are categorized
into two categories and further sub-categorized into seven different functions
under each category. The categories are:
Aggregate functions:
These functions are used to do operations from the values of the column and a
single value is returned.
Scalar functions:
These functions are based on user input, these too return a single value.
[Link] operator is used in queries for pattern matching?
LIKE operator: It is used to fetch filtered data by searching for a particular
pattern in the where clause.
Syntax:
SELECT column1,column2 FROM table_name WHERE column_name LIKE pattern;
LIKE: operator name
[Link] SQL Having statement?
HAVING is used to specify a condition for a group or an aggregate function used in
the select statement. The WHERE clause selects before grouping. The HAVING clause
selects rows after grouping. Unlike the HAVING clause, the WHERE clause cannot
contain aggregate functions
[Link] SQL AND OR statement with an example?
In SQL, the AND & OR operators are used for filtering the data and getting precise
results based on conditions.
The AND and OR operators are used with the WHERE clause.
These two operators are called conjunctive operators.
AND Operator: This operator displays only those records where both conditions
condition 1 and condition 2 evaluate to True.
OR Operator: This operator displays the records where either one of the conditions
condition 1 and condition 2 evaluates to True. That is, either condition1 is True
or condition2 is True.
[Link] BETWEEN statements in SQL?
The SQL BETWEEN condition allows you to easily test if an expression is within a
range of values (inclusive). The values can be text, date, or numbers. It can be
used in a SELECT, INSERT, UPDATE, or DELETE statement. The SQL BETWEEN Condition
will return the records where the expression is within the range of value1 and
value2
[Link] do we use Commit and Rollback commands?
COMMIT
ROLLBACK
COMMIT permanently saves the changes made by the current transaction.
ROLLBACK undo the changes made by the current transaction.
The transaction can not undo changes after COMMIT execution.
Transaction reaches its previous state after ROLLBACK.
When the transaction is successful, COMMIT is applied. When
the transaction is aborted, ROLLBACK occurs.
[Link] are ACID properties?
A transaction is a single logical unit of work that accesses and possibly modifies
the contents of a database. Transactions access data using read-and-write
operations. In order to maintain consistency in a database, before and after the
transaction, certain properties are followed. These are called ACID properties.
ACID (Atomicity, Consistency, Isolation, Durability) is a set of properties that
guarantee that database transactions are processed reliably.
69. Are NULL values the same as zero or a blank space?
In SQL, zero or blank space can be compared with another zero or blank space.
whereas one null may not be equal to another null. null means data might not be
provided or there is no data.
70. What is the need for group functions in SQL?
In database management, group functions, also known as aggregate functions, is a
function where the values of multiple rows are grouped together as input on certain
criteria to form a single value of more significant meaning.
Various Group Functions
1) Count()
2) Sum()
3) Avg()
4) Min()
5) Max()
71. How can you fetch common records from two tables?
The below statement could be used to get data from multiple tables, so, we need to
use join to get data from multiple tables.
Syntax :
SELECT [Link], [Link]
FROM tablenmae1
JOIN tablename2
ON [Link] = [Link]
ORDER BY columnname;
[Link] are the advantages of PL/SQL functions?
The advantages of PL / SQL functions are as follows:
We can make a single call to the database to run a block of statements. Thus, it
improves the performance against running SQL multiple times. This will reduce the
number of calls between the database and the application.
We can divide the overall work into small modules which becomes quite manageable,
also enhancing the readability of the code.
It promotes reusability.
It is secure since the code stays inside the database, thus hiding internal
database details from the application(user). The user only makes a call to the
PL/SQL functions. Hence, security and data hiding is ensured.
[Link] is the SQL query to display the current date?
CURRENT_DATE returns to the current date. This function returns the same value if
it is executed more than once in a single statement, which means that the value is
fixed, even if there is a long delay between fetching rows in a cursor.
Syntax:
CURRENT_DATE
or
CURRENT DATE
[Link] to find the available constraint information in the table?
In SQL Server the data dictionary is a set of database tables used to store
information about a database’s definition. One can use these data dictionaries to
check the constraints on an already existing table and to change them(if possible)
75. What is SQL injection?
SQL injection is a technique used to exploit user data through web page inputs by
injecting SQL commands as statements. Basically, these statements can be used to
manipulate the application’s web server by malicious users.
SQL injection is a code injection technique that might destroy your database.
SQL injection is one of the most common web hacking techniques.
SQL injection is the placement of malicious code in SQL statements, via web page
input.
[Link] do we avoid getting duplicate entries in a query without using the distinct
keyword?
DISTINCT is useful in certain circumstances, but it has drawbacks that it can
increase the load on the query engine to perform the sort (since it needs to
compare the result set to itself to remove duplicates). We can remove duplicate
entries using the following options:
Remove duplicates using row numbers.
Remove duplicates using self-Join.
Remove duplicates using group by.
[Link] is Case WHEN in SQL?
Control statements form an important part of most languages since they control the
execution of other sets of statements. These are found in SQL too and should be
exploited for uses such as query filtering and query optimization through careful
selection of tuples that match our requirements. In this post, we explore the Case-
Switch statement in SQL. The CASE statement is SQL’s way of handling if/then logic.
syntax: 1
CASE case_value WHEN when_value THEN statement_list [WHEN when_value THEN
statement_list] … [ELSE statement_list]END CASE
[Link] the operator which is used in the query for appending two strings?
In SQL for appending two strings, the ” Concentration operator” is used and its
symbol is ” || “.
[Link] is the DDL and DML?
Data Definition Language (DDL) statements describe the structure of a database or
schema. Data Manipulation Language (DML) statements, on the other hand, allow
altering data that already exists in the database.
[Link] is TCL and DCL?
Data Definition Language (DDL) Data Query Language (DQL) Data Manipulation Language
(DML) Data Control Language (DCL) Transaction Control Language (TCL).28 Mar 2023
[Link] do you mean by DCL?
A data control language (DCL) is a syntax similar to a computer programming
language used to control access to data stored in a database (authorization). In
particular, it is a component of Structured Query Language (SQL).
[Link] is TCL in database?
What Is The Full Form Of TCL? The full form of TCL is Transaction Control Language.
TCL commands are basically used for managing and controlling the transactions in a
database to maintain consistency. And it also helps a user manage all the changes
made by the DML commands for maintaining its transactions.
[Link] is the importance of SQL joins in database management?
SQL joins are important in database management for the following reasons:
A method of stitching a database back together to make it easier to read and use.
Additionally, they maintain a normalized database. Data normalization helps us keep
data redundancy low so that when we delete or update a record, we will have fewer
data anomalies in our application.
Joins have the advantage of being faster, and as a result, are more efficient.
It is almost always faster to retrieve the data using a join query rather than one
that uses a subquery.
By utilizing joins, it is possible to reduce the workload on the database. For
example, instead of multiple queries, you can use one join query. So, you can
better utilize the database's ability to search, filter, sort, etc.
[Link] merge join in SQL.
Merge join produces a single output stream resulting from the joining of two sorted
datasets using an INNER, FULL, or LEFT join. It is the most effective of all the
operators for joining data. Specifically, merge join requires that both inputs be
sorted as well as matching meta-data in the joined columns. Users can't join
columns of different data types together. Users are not permitted to combine a
column with a numeric data type with a column with a character data type.
85. State the difference between inner join and left join.
Inner Join: This join generates datasets that contain matching records in both
tables (left and right). By using an inner join, only the rows that match between
each of the tables are returned; all non-matching rows are removed.
[Link] difference between left join and right join.
Left Join: It returns datasets that have matching records in both tables (left and
right) plus non-matching rows from the left table. By using a left join, all the
records in the left table plus the matching records in the right table are
returned.
[Link] you explain nested join in SQL?
A JOIN is one of the mechanisms that we use to combine the data of more than one
table in a relational database, and a Nested Join is one of the simplest methods
involving the physical joining of two tables. In essence, a Nested Join uses one
joining table as an outer input table while the other one serves as an inner input
table. With a Nested Loop Join, one row from the outer table is retrieved and then
the row is searched for in the inner table; this process is repeated until all the
output rows from the outer table have been searched for in the inner table. Nested
Loop Join may further be sub-categorized into Indexed Nested, Naive Nested and
Temporary Index Nested Loop Join.
[Link] can you join a table to itself?
Another type of join in SQL is a SELF JOIN, which connects a table to itself. In
order to perform a self-join, it is necessary to have at least one column (say X)
that serves as the primary key as well as one column (say Y) that contains values
that can be matched with those in X. The value of Column Y may be null in some
rows, and Column X need not have the exact same value as Column Y for every row.
[Link] natural join.
Natural Joins are a type of join that combines tables based on columns that share
the same name and have the same datatype. Ideally, there should be a common
attribute (column) among two tables in order to perform a natural join.
Syntax:
SELECT * FROM TableName1 NATURAL JOIN TableName2;
[Link] difference between Full Join and Cross Join.
Cross Join: A Cross Join is also referred to as a Cartesian join or Cartesian
product. The result set of a cross join is equal to all of the rows from the first
table multiplied by all of the rows from the second table. It applies to all
columns.
Syntax:
SELECT * FROM Table_1 CROSS JOIN Table_