SQL Question
SQL Question
SQL stands for the Structured Query Language. It is the standard language
used to maintain the relational database and perform many different data
manipulation operations on the data. It is a database language used for
database creation, deletion, fetching and modifying rows, etc. sometimes
usages of SQL?
SQL is responsible for maintaining the relational data and the data
structures present in the database. Some of the common usages are given
below:
5
SQL refers to the Standard Query Language. so, it is true that SQL is a
language but does not actually support the programming language. It is a
common language that doesn't have a loop, conditional statements, and
logical operations. It cannot be used for anything other than data
manipulation. It is a command language to perform database operations.
The primary purpose of SQL is to retrieve, manipulate, update, delete, and
perform complex operations like joins on the data present in the database.
subsets of SQL?
The following are the four significant subsets of the SQL:
DDL stands for Data definition language. It is the subset of a database that
defines the data structure of the database when the database is created. we
can use the DDL commands to add, remove, or modify tables. It consists of
the following commands: CREATE, ALTER and DELETE database objects
such as schema, tables, indexes, view, sequence, etc.
Example
of DML Language?
Example
Example
Example
Table: Student
The foreign key is used to link one or more tables together. It is also known
as the referencing key. A foreign key is specified as a key that is related to
the primary key of another table. It means a foreign key field in one table
refers to the primary key field of the other table. It identifies each row of
another table uniquely that maintains the referential integrity. The primary
key-foreign key relationship is a very crucial relationship as it maintains the
ACID properties of the database sometimes. It also prevents actions that
would destroy links between the child and parent tables.
We can define a foreign key into a table as follows:
1. CONSTRAINT constraint_name]
2. FOREIGN KEY [foreign_key_name] (col_name, ...)
3. REFERENCES parent_tbl_name (col_name,...)
A unique key is a single or combination of fields that ensure all values stores
in the column will be unique. It means a column cannot stores duplicate
values. This key provides uniqueness for the column or set of columns. For
example, the email addresses and roll numbers of student's tables should
be unique. It can accept a null value but only one null value per column. It
ensures the integrity of the column or group of columns to store different
values into a table.
.
between a primary key & unique key?
The primary key and unique key both are essential constraints of the SQL.
The main difference among them is that the primary key identifies each
record in the table. In contrast, the unique key prevents duplicate entries in
a column except for a NULL value. The following comparison chart explains
it more clearly:
o Software
o Data
o Procedures
o Database Languages
o Query Processor
o Database Manager
o Database Engine
o Reporting
o Unique Index
o Clustered Index
o Non-Clustered Index
o Bit-Map Index
o Normal Index
o Composite Index
o B-Tree Index
o Function-Based Index
Example
1. CREATE TABLE Employee(
2. ID int AUTO_INCREMENT PRIMARY KEY,
3. Name varchar(45),
4. Phone varchar(15),
5. City varchar(25),
6. );
A clustered index is actually a table where the data for the rows are stored.
It determines the order of the table data based on the key values that can
sort in only one direction. Each table can have only one clustered index. It
is the only index, which has been automatically created when the primary
key is generated. If many data modifications needed to be done in the
table, then clustered indexes are preferred.
The indexes other than PRIMARY indexes (clustered indexes) are called
non-clustered indexes. We know that clustered indexes are created
automatically when primary keys are generated, and non-clustered indexes
are created when multiple joins conditions and various filters are used in
the query. The non-clustered index and table data are both stored in
different places. It cannot be able to alter the physical order of the table
and maintains the logical order of data.
The purpose of creating a non-clustered index is for searching the data. Its
best example is a book where the content is written in one place, and the
index is at a different place. We can create 0 to 249 non-clustered indexes
in each table. The non-clustered indexing improves the performance of the
queries which use keys without assigning the primary key.
30) What are the differences between SQL, MySQL, and SQL Server?
SQL has no variables. MySQL can use SQL Server can use
variables constraints variables constraints
and data types. and data types.
SQL PL/SQL
SQL can directly interact PL/SQL cannot directly interact with the
with the database server. database server.
Yes. We can use the alias method in the ORDER BY instead of the WHERE
clause for sorting a column.
33) What is the difference between clustered and non-clustered indexes in SQL?
Indexing is a method to get the requested data very fast. There are mainly
two types of indexes in SQL, clustered index and non-clustered index. The
differences between these two indexes are very important from an SQL
performance perspective. The following comparison chart explains their
main differences:
A clustered index is a table or view where the data The indexes other than
for the rows are stored. In a relational database, if PRIMARY indexes
the table column contains a primary key, MySQL (clustered indexes) are
automatically creates a clustered index named called non-clustered
PRIMARY. indexes. It has a structure
separate from the data row.
The non-clustered indexes
are also known as
secondary indexes.
Clustered indexes store the data information and the Non-clustered indexes
data itself. stores only the information,
and then it will refer you to
the data stored in clustered
data.
There can only be one clustered index per table. There can be one or more
non-clustered indexes in a
table.
SQL joins are used to retrieve data from multiple tables into a meaningful
result set. It is performed whenever you need to fetch records from two or
more tables. They are used with SELECT statement and join conditions.
o INNER JOIN
o LEFT OUTER JOIN
o RIGHT OUTER JOIN
Joins are used to merge two tables or retrieve data from tables. It depends
on the relationship between tables. According to the ANSI standard, the
following are the different types of joins used in SQL:
o INNER JOIN
o SELF JOIN
o LEFT OUTER JOIN
o RIGHT OUTER JOIN
o FULL OUTER JOIN
o CROSS JOIN
1. SELECT column_lists
2. FROM table1
3. INNER JOIN table2 ON join_condition1
4. INNER JOIN table3 ON join_condition2
5. ...;
1. SELECT colum_lists
2. FROM table1
3. RIGHT JOIN table2
4. ON join_condition;
The Left Join is used to fetch all rows from the left-hand table and common
records between the specified tables. It returns all the rows from the left-
hand side table even though there are no matches on the right-hand side
table. If it will not find any matching record from the right side table, then
it returns null. This join can also be called a Left Outer Join.
1. SELECT colum_lists
2. FROM table1
3. LEFT JOIN table2
4. ON join_condition;
The Full Join results from a combination of both left and right join that
contains all the records from both tables. It fetches 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
tables. If a match is not found, it puts NULL value. It is also known as FULL
OUTER JOIN.
The following visual representation explains it more clearly:
SQL triggers have two main components one is action, and another is an
event. When certain actions are taken, an event occurs as a result of those
actions.
We use the CREATE TRIGGER statement for creating a trigger in SQL. Here
is the syntax:
A SELF JOIN is used to join a table with itself. This join can be performed
using table aliases, which allow us to avoid repeating the same table name
in a single sentence. It will throw an error if we use the same table name
more than once in a single query without using table aliases.
A SELF JOIN is required when we want to combine data with other data in
the same table itself. It is often very useful to convert a hierarchical structure
to a flat structure.
1. SELECT column_lists
2. FROM table1 AS T1, table1 AS T2
3. WHERE join_conditions;
Example
If we want to get retrieve the student_id and name from the table where
student_id is equal, and course_id is not equal, it can be done by using the
self-join:
We use the set operators to merge data from one or more tables of the
same kind. Although the set operators are like SQL joins, there is a
significant distinction. SQL joins combine columns from separate tables,
whereas SQL set operators combine rows from different queries. SQL
queries that contain set operations are called compound queries. The set
operators in SQL are categories into four different types:
A. UNION: It combines two or more results from multiple SELECT queries
into a single result set. It has a default feature to remove the duplicate rows
from the tables. The following syntax illustrates the Union operator:
B. UNION ALL: This operator is similar to the Union operator, but it does
not remove the duplicate rows from the output of the SELECT statements.
The following syntax illustrates the UNION ALL operator:
D. MINUS: This operator returns the records from the first query, which is
not found in the second query. It does not return duplicate values. The
following syntax illustrates the MINUS operator:
The constraint is used to specify the rule and regulations that allows or
restricts what values/data will be stored in the table. It ensures data
accuracy and integrity inside the table. It enforces us to store valid data and
prevents us from storing irrelevant data. If any interruption occurs between
the constraint and data action, the action is failed. Some of the most
commonly used constraints are NOT NULL, PRIMARY KEY, FOREIGN KEY,
AUTO_INCREMENT, UNIQUE KEY, etc.
48) What is the difference between DELETE and TRUNCATE statements in SQL?
The main difference between them is that the delete statement deletes data
without resetting a table's identity, whereas the truncate command resets
a particular table's identity. The following comparison chart explains it more
clearly:
No. DELETE TRUNCATE
The ACID properties are meant for the transaction that goes through a
different group of tasks. A transaction is a single logical order of data. It
provides properties to maintain consistency before and after the
transaction in a database. It also ensures that the data transactions are
processed reliably in a database system.
The ACID property is an acronym for Atomicity, Consistency, Isolation, and
Durability.
Consistency: This property ensures that the data must meet all validation
rules. In simple words, we can say that the database changes state only
when a transaction will be committed successfully. It also protects data
from crashes.
No. The NULL value is not the same as zero or a blank space. The following
points explain their main differences:
SQL functions are simple code snippets that are frequently used and re-
used in database systems for data processing and manipulation. Functions
are the measured values. It always performs a specific task. The following
rules should be remembered while creating functions:
o A function should have a name, and the name cannot begin with a
special character such as @, $, #, or other similar characters.
o Functions can only work with the SELECT statements.
o Every time a function is called, it compiles.
o Functions must return value or result.
o Functions are always used with input parameters.
52) What is meant by case manipulation functions? Explains its different types in SQL.
Output: Information-technology
Output: Management
Output: 16
Output: 7
E) LPAD: It returns the padding of the left-side character value for right-
justified value. For example:
F) RPAD: It returns the padding of the right-side character value for left-
justified value. For example:
Output: 200***
G) TRIM: This function is used to remove all the defined characters from
the beginning, end, or both. It also trimmed extra spaces. For example:
Output: BCDCB
Input: SELECT REPLACE ( 'It is the best coffee at the famous coffee shop.',
'coffee', 'tea');
The NVL() function is used to convert the NULL value to the other value.
The function returns the value of the second parameter if the first
parameter is NULL. If the first parameter is anything other than NULL, it is
left unchanged. This function is used in Oracle, not in SQL and MySQL.
Instead of NVL() function, MySQL have IFNULL() and SQL Server have
ISNULL() function.
56) What are the syntax and use of the COALESCE function?
The COALESCE() function evaluates the arguments in sequence and returns
the first NON-NULL value in a specified number of expressions. If it
evaluates arguments as NULL or not found any NON-NULL value, it returns
the NULL result.
Example:
The DISTINCT keyword is used to ensure that the fetched value always has
unique values. It does not allow to have duplicate values. The DISTINCT
keyword is used with the SELECT statement and retrieves different values
from the table's column. We can use it with the help of the following syntax:
If we want to get the name column without any duplicate values, the
DISTINCT keyword is required. Executing the below command will return a
name column with unique values.
58) What is the default ordering of data using the ORDER BY clause? How could it be changed?
The ORDER BY clause is used to sort the table data either in ascending or
descending order. By default, it will sort the table in ascending order. If we
want to change its default behavior, we need to use the DESC keyword after
the column name in the ORDER BY clause.
In the below output, we can see that the first query will sort the table data
in ascending order based on the name column. However, if we run the
second query by specifying the DESC keyword, the table's order is changed
in descending order.
Answer: No. The above query does not return the output because we
cannot use the WHERE clause to restrict the groups. We need to use the
HAVING clause instead of the WHERE clause to get the correct output.
60) What is the difference between the WHERE and HAVING clauses?
The main difference is that the WHERE clause is used to filter records before
any groupings are established, whereas the HAVING clause is used to filter
values from a group. The below comparison chart explains the most
common differences:
WHERE HAVING
This clause is implemented in row This clause is implemented in
operations. column operations.
This clause can be used with the This clause can only be used
SELECT, UPDATE, and DELETE with the SELECT statement.
statements.
SQL provides seven (7) aggregate functions, which are given below:
SQL injection is a type of vulnerability in website and web app code that
allows attackers to control back-end operations and access, retrieve, and
destroy sensitive data from databases. In this technique, malicious SQL
statements are inserted into a database entry field, and once they are
performed, the database becomes vulnerable to an attacker. This technique
is commonly used to access sensitive data and perform administrative
activities on databases by exploiting data-driven applications. It is also
known as SQLi attack.
63) What is the difference between the RANK() and DENSE_RANK() functions?
The RANK function determines the rank for each row within your ordered
partition in the result set. If the two rows are assigned the same rank, then
the next number in the ranking will be its previous rank plus a number of
duplicate numbers. For example, if we have three records at rank 4, the next
rank listed would be ranked 7.
The DENSE_RANK function assigns a unique rank for each row within a
partition as per the specified column value without any gaps. It always
specifies ranking in consecutive order. If the two rows are assigned the
same rank, this function will assign it with the same rank, and the next rank
being the next sequential number. For example, if we have 3 records at rank
4, the next rank listed would be ranked 5.
Yes. We can implicitly insert a row for the identity column. Here is an
example of doing this: