0% found this document useful (0 votes)
8 views98 pages

SQL Database

The document discusses SQL and relational database concepts. It defines SQL as a standard language for performing tasks like data retrieval, insertion, updating, and deletion from a database. It also defines a database as an organized collection of data for easy access and management. The document provides examples of relational database management systems like SQL Server, Oracle, and MySQL that use SQL to communicate with databases.

Uploaded by

Raj Latte
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
8 views98 pages

SQL Database

The document discusses SQL and relational database concepts. It defines SQL as a standard language for performing tasks like data retrieval, insertion, updating, and deletion from a database. It also defines a database as an organized collection of data for easy access and management. The document provides examples of relational database management systems like SQL Server, Oracle, and MySQL that use SQL to communicate with databases.

Uploaded by

Raj Latte
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 98

LET'S

TALK
ABOUT
SQL
A DATABASE LANGUAGE THAT IS
USED IN MOST OF THE DATABASES
IN THE WORLD

@the_master_graduates www.master-graduates.com
D A I L Y S Q L

What is Relational Database Management System


(RDMBS)?

RDBMS store data into a collection of tables, which


is related by common fields between the columns
of the table. It also provides relational operators
to manipulate the data stored into the tables.

Example: SQL Server, Oracle, and MySQL.

@the_master_graduates
D A I L Y S Q L

What is Structured Query Language (SQL)?

SQL stands for Structured Query Language , and it


is used to communicate with the Database. This is
a standard language used to perform tasks such as
retrieval, updates, insertion and deletion of data
from a database.

@the_master_graduates
D A I L Y S Q L

What is a Database?

A Database is an organized form of data for easy


access, storing, retrieval and managing of data.
This is also known as structured form of data
which can be accessed in many ways.

Example: School Management Database, Bank


Management Database, and HR dat.

@the_master_graduates
D A I L Y S Q L

What is Primary Key?

A primary key is a combination of fields which


uniquely specify a row. This is a special kind of
unique key, and it has implicit NOT NULL
constraint. This means, Primary key values cannot
be NULL.

@the_master_graduates
D A I L Y S Q L

What is a Unique Key?

A Unique key constraint uniquely identifies each


record in a database. This provides uniqueness for
the column or set of columns. A Primary key
constraint has automatic unique constraint
defined on it. There can be many unique
constraints defined per table, but only one Primary
key constraint defined per table.

@the_master_graduates
D A I L Y S Q L

What is a Foreign Key?

A foreign key is one table which can be related to


the primary key of another table. Relationships
need to be created between two tables by
referencing the foreign key with the primary key of
another table.

@the_master_graduates
D A I L Y S Q L

Explain the difference between Spreadsheets and


Databases.

Spreadsheet: A file that exists of cells in rows


and columns and can help arrange, calculate
and sort data. It can have numeric values, text,
formulas and functions. It features columns and
rows to keep inserted information legible and
simple to understand. It is an electronic graph
sheet.

Database: It is an organized collection of data


arranged for ease and speed of search and
retrieval. It contains multiple tables. A database
engine can sort, change or serve the
information on the database. Basically, it is a
set of information which is held in a computer.

@the_master_graduates
D A I L Y S Q L

What are TABLE and FIELDS?

A table is a set of data that are organized in a


model with Columns and Rows. Columns can be
categorized as vertical, and Rows are horizontal. A
table has a specified number of column called
fields but can have any number of rows which are
called records.

Example:
Table: Employee.
Field: Emp ID, Emp Name, Date of Birth.
Data: 201456, David, 01/16/1989.

@the_master_graduates
D A I L Y S Q L

There are five types of SQL commands: DDL, DML,


DCL, TCL, and DQL.

Data Definition Language (DDL): DDL changes the


structure of the table like creating a table,
deleting a table, altering a table, etc. All the
commands of DDL are auto-committed which
means that it permanently saves all the changes in
the database.

DDL Commands:
CREATE; ALTER; DROP; TRUNCATE

@the_master_graduates
D A I L Y S Q L

Data Manipulation Language (DML): DML


commands are used to modify the database. It is
responsible for all forms of changes in the
database. The commands of DML are not auto-
committed which means
that it can't permanently save all the changes in
the database.

DML Commands:
INSERT; UPDATE; DELETE

@the_master_graduates
D A I L Y S Q L

Transaction Control Language(TCL): TCL


commands can only be used with DML commands
like INSERT, DELETE and UPDATE. These operations
are automatically committed in the database,
which is why they cannot be used while creating
tables or dropping them.

TCL Commands:
COMMIT; ROLLBACK; SAVEPOINT

@the_master_graduates
D A I L Y S Q L

Data Control Language (DCL): DCL commands are


used to grant and take back authority from any
database user.

DCL Commands:
Grant; Revoke

Data Query Language (DQL): DQL is used to fetch


the data from the database and It uses only one
command:

DQL Commands:
SELECT

@the_master_graduates
D A I L Y S Q L

What is normalization?

Normalization is the process of minimizing


redundancy and dependency by organizing fields
and tables of a database. The main aim of
Normalization is to add, delete or modify fields
that can be made in a single table.

What is denormalization?

Denormalization is a technique used to access the


data from higher to lower normal forms of
database. It is also a process of introducing
redundancy into a table by incorporating data
from the related tables.

@the_master_graduates
D A I L Y S Q L

Explain the different types of normalization.

First Normal Form (1NF): This should remove all the


duplicate columns from the table. Creation of tables for
the related data and identification of unique columns.

Second Normal Form (2NF): Meeting all requirements of


the first normal form. Placing the subsets of data in
separate tables and Creation of relationships between
the tables using primary keys.

Third Normal Form (3NF): This should meet all


requirements of 2NF. Removing the columns which are
not dependent on primary key constraints.

Fourth Normal Form (4NF): Meeting all the requirements


of third normal form and it should not have multi- valued
dependencies.

@the_master_graduates
D A I L Y S Q L

What are views in SQL?

A view is a virtual table which consists of a subset


of data contained in a table. Views are not virtually
present, and it takes less space to store. View can
have data of one or more tables combined, and it
is depending on the relationship.

@the_master_graduates
D A I L Y S Q L

What is join?

This is a keyword used to query data from more


tables based on the relationship between the
fields of the tables. Keys play a major role when
JOINs are used. There are various types of joins
which can be used to retrieve data and it depends
on the relationship between tables.

@the_master_graduates
D A I L Y S Q L

Explain different types of Joins.

Left Outer Join: If we want all the records from left


table and only matching records from right table
then will use left outer join/left join.

Right Outer Join: If we want to display all the


records from right table and only matching
records from left table then will right outer
join/right join.

Full Outer Join: If we want to display all the


records from both the tables then will use full
outer join.

Inner Join: If we want only the matching records


from both the tables then will use Inner
join/Simple join.

@the_master_graduates
D A I L Y S Q L

What are the different types of indexes?

An index is a performance tuning method of allowing faster


retrieval of records from the table. An index creates an
entry for each value and makes it faster to retrieve data.

Three types of indexes:

Unique Index: This indexing does not allow the field to have
duplicate values if the column is unique indexed. Unique
index can be applied automatically when primary key is
defined.

Clustered Index: This type of index reorders the physical


order of the table and search based on the key values. Each
table can have only one clustered index.

Non-Clustered Index: Non-Clustered Index does not alter


the physical order of the table and maintains logical order
of data. Each table can have 999 nonclustered indexes.

@the_master_graduates
D A I L Y S Q L

What is a cursor in SQL?

A database Cursor is a control which enables


traversal over the rows or records in the table.
This can be viewed as a pointer to one row in a set
of rows. Cursor is very much useful for traversing
such as for retrieval, addition
and removal of database records.

@the_master_graduates
D A I L Y S Q L

What is query?

A database query is a code written in order to get


the information back from the database. Queries
can be designed in such a way that it matches with
our expectation of the result set.

@the_master_graduates
D A I L Y S Q L

What is a subquery and its types?

A subquery is a query within another query. The


outer query is called as main query, and inner
query is called subquery. SubQuery is always
executed first, and the result of subquery is
passed on to the main query.

There are two types of subquery – Correlated and


NonCorrelated. A correlated subquery cannot be
considered as an independent query, whereas a
Non-Correlated sub query can be considered as
independent query and the output of subquery are
substituted in the main query.

@the_master_graduates
D A I L Y S Q L

What is a trigger?

A DB trigger is a code or programs that


automatically execute with response to some
event on a table or view in a database. Mainly,
trigger helps to maintain the integrity of the
database.

Example: When a new student is added to the


student database, new records should be created
in the related tables such as the Exam, Score and
Attendance tables.

@the_master_graduates
D A I L Y S Q L

Differentiate between the DELETE and TRUNCATE


commands.

DELETE command is used to remove rows from


the table, and WHERE clause can be used for
conditional set of parameters. Commit and
Rollback can be performed after delete
statement.

TRUNCATE removes all rows from the table.


Truncate operation cannot be rolled back.

@the_master_graduates
D A I L Y S Q L

What are local and global variables?

Local variables are the variables which can be


used or exist inside the function. They are not
known to the other functions and those
variables cannot be referred to or used.
Variables can be created whenever that
function is called.

Global variables are the variables which can be


used or exist throughout the program. Same
variable declared in global cannot be used in
functions. Global variables cannot be created
whenever that function is called.

@the_master_graduates
D A I L Y S Q L

What are constraints?

Constraint can be used to specify the limit on the


data type of table. Constraint can be specified
while creating or altering the table statement.

Following are some of the constraints:

NOT NULL
UNIQUE
CHECK
DEFAULT

@the_master_graduates
D A I L Y S Q L

What is data integrity?

Data Integrity defines the accuracy and


consistency of data stored in a database. It can
also define integrity constraints to enforce
business rules on the data when it is entered into
the application or database.

@the_master_graduates
D A I L Y S Q L

What is auto increment?

Auto increment keyword allows the user to create


a unique number to be generated when a new
record is inserted into the table. AUTO INCREMENT
keyword can be used in Oracle and IDENTITY
keyword can be used in SQL SERVER.

@the_master_graduates
D A I L Y S Q L

What is a data warehouse?

Data warehouses are a central repository of data


from multiple sources of information. This data is
consolidated, transformed and made available for
the mining and online processing. Warehouse data
have subsets of data called Data Marts.

@the_master_graduates
D A I L Y S Q L

What is the difference between DROP and


TRUNCATE statements?

TRUNCATE removes all the rows from the table,


and it cannot be rolled back.

DROP command removes a table from the


database and operation cannot be rolled back.

@the_master_graduates
D A I L Y S Q L

What are aggregate and scalar functions?

Functions are methods used to perform data


operations. SQL has many in-built functions used
to perform string concatenations, mathematical
calculations etc.

SQL functions are categorized into two categories:

Aggregate SQL Functions: The Aggregate


Functions in SQL perform calculations on a
group of values and then return a single value.

Scalar SQL Functions: The Scalar Functions in


SQL are used to return a single value from the
given input value.

@the_master_graduates
D A I L Y S Q L

What is alias in SQL?

SQL aliases are used to give a table, or a column in


a table, a temporary name. Aliases are often used
to make column names more readable. An alias
only exists for the duration of that query. An alias
is created with the AS keyword.

@the_master_graduates
D A I L Y S Q L

What is the difference between OLTP and OLAP?

OLAP is Online Analytical Processing, a category of


software tools which provide analysis of data for
business decisions. OLAP systems allow users to analyze
database information from multiple database systems at
one time. The primary objective is data analysis and not
data processing.

OLTP is Online transaction processing shortly known as


OLTP supports transaction-oriented applications in a
3tier architecture. OLTP administers day to day
transaction of an organization. The primary objective is
data processing and not data analysis. Unlike OLAP
systems, the goal of OLTP systems is serving real-time
transactions.

@the_master_graduates
D A I L Y S Q L

What is collation?

Collation is defined as a set of rules that


determine how character data can be sorted and
compared. ASCII value can be used to compare
these character data.

@the_master_graduates
D A I L Y S Q L

What are the various 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
(fullwidth) are treated differently.

@the_master_graduates
D A I L Y S Q L

How can we create tables in SQL?

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 data types.

For example, if we want to create employee table:

CREATE TABLE employee(


name varchar(25),
age int,
gender varchar(25)
);

@the_master_graduates
D A I L Y S Q L

How can we insert data in SQL?

Specify both the column names and the values


to be inserted:

INSERT INTO table_name ( column1,column2, ...)


VALUES (value1, value2, ...);

If you are adding values for all the columns of


the table, you do not need to specify the
column names in the SQL query. However, make
sure the order of the values is in the same order
as the columns in the table.

INSERT INTO table_name


VALUES (value1, value2, value3, ...);

@the_master_graduates
D A I L Y S Q L

How can we change a table name in SQL?

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:

ALTER TABLE employee


RENAME TO employee_information;

@the_master_graduates
D A I L Y S Q L

What is SQL server?

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.

@the_master_graduates
D A I L Y S Q L

What is ETL in SQL?

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, we have
our raw data. This raw data has to be transformed
into a 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.

@the_master_graduates
D A I L Y S Q L

What are nested queries?

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.

@the_master_graduates
D A I L Y S Q L

What is the difference between CHAR and


VARCHAR2 data types in SQL server?

When stored in a database, varchar2 uses only the


allocated space. E.g. if you have a varchar2(1999)
and put 50 bytes in the table, it will use 52 bytes.
But when stored in a database, char always uses
the maximum length and is blank-padded. E.g. if
you have char(1999) and put 50 bytes in the table,
it will consume 2000 bytes.

@the_master_graduates
D A I L Y S Q L

What is difference between SQL and PL/SQL?

SQL is a Structured Query Language to create and


access databases whereas PL/SQL comes with
procedural concepts of programming languages.

@the_master_graduates
D A I L Y S Q L

What is the difference between SQL and MySQL?

SQL is a Structured Query Language that is used


for manipulating and accessing the relational
database. On the other hand, MySQL itself is a
relational database that uses SQL as the standard
database language.

@the_master_graduates
D A I L Y S Q L

What is cross join?

Cross join is a Cartesian product where number of


rows in the first table multiplied by number of
rows in the second table.

@the_master_graduates
D A I L Y S Q L

What are user-defined functions?

User-defined functions are the functions written


to use that logic whenever required. It is not
necessary to write the same logic several times.
Instead, function can be called or executed
whenever needed.

@the_master_graduates
D A I L Y S Q L

What is a CLAUSE?

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.

@the_master_graduates
D A I L Y S Q L

What is recursive stored procedure?

This is 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_master_graduates
D A I L Y S Q L

Explain UNION, MINUS and INTERACT commands?

UNION operator is used to combine the results


of two tables, and it eliminates duplicate rows
from the tables.

MINUS operator is used to return rows from the


first query but not from the second query.
Matching records of first and second query and
other rows from the first query will be displayed
as a result set.

INTERSECT operator is used to return rows


returned by both the queries.

@the_master_graduates
D A I L Y S Q L

Which operator is used in query for pattern


matching?

LIKE operator is used for pattern matching, and it


can be used with:
% - Matches zero or more characters.
_(Underscore) – Matching exactly one character.

@the_master_graduates
D A I L Y S Q L

How can we select unique records from a Table?

Select unique records from a table by using


DISTINCT keyword.

Example:
SELECT DISTINCT column1, column2, ...
FROM table_name;

@the_master_graduates
D A I L Y S Q L

What is the main difference in the BETWEEN and


IN condition operators?

BETWEEN operator is used to display rows based


on a range of values in a row whereas the IN
condition operator is used to check for values
contained in a specific set of values.

Example of BETWEEN:
SELECT * FROM Students
where ROLL_NO BETWEEN 10 AND 50;

Example of IN: SELECT * FROM students where


ROLL_NO IN (8,15,25);

@the_master_graduates
D A I L Y S Q L

What are SQL functions used for?

SQL functions are used for the following purposes:

To perform some calculations on the data


To modify individual data items
To manipulate the output
To format dates and numbers
To convert the data types

@the_master_graduates
D A I L Y S Q L

What is the need for MERGE statement?

This statement allows conditional update or


insertion of data into a table. It performs an
UPDATE if a row exists, or an INSERT if the row
does not exist.

List ways in which dynamic SQL can be executed.

Write a query with parameters.


Using EXEC.
Using sp_executesql.

@the_master_graduates
D A I L Y S Q L

List some case manipulation functions in SQL.

There are 3 case manipulation functions in SQL:

LOWER: This function returns the string in


lowercase. It takes a string as an argument and
returns it by converting it into lower case.
Syntax: LOWER(‘string’)

UPPER: This function returns the string in


uppercase. It takes a string as an argument and
returns it by converting it into uppercase.
Syntax: UPPER(‘string’)

INITCAP: This function returns the string with


the first letter in uppercase and rest of the
letters in lowercase. Syntax: INITCAP(‘string’)

@the_master_graduates
D A I L Y S Q L

Is semicolon used after SQL? Justify why or why


not.

Some database systems require a semicolon at the


end of each SQL statement. Semicolon is the
standard way to separate each SQL statement in
database systems that allow more than one SQL
statement to be executed in the same call to the
server.

@the_master_graduates
D A I L Y S Q L

What is candidate key?

A candidate key is a subset of a super key set


where the key which contains no redundant
attribute is none other than a Candidate Key. In
order to select the candidate keys from the set of
super key, we need to look at the super key set.

@the_master_graduates
D A I L Y S Q L

What is the difference between JOIN and UNION?

JOIN in SQL is used to combine data from many


tables based on a matched condition between
them. The data combined using JOIN statement
results into new columns.

UNION in SQL is used to combine the result-set


of two or more SELECT statements. The data
combined using UNION statement results into
new distinct rows.

@the_master_graduates
D A I L Y S Q L

What is the difference between order and group


by?

The ORDER BY clause is used in SQL queries to sort


the data returned by a query in ascending or
descending order. If we omit the sorting order, it
sorts the summarized result in the ascending order
by default. The ORDER BY clause, like the GROUP
BY clause, could be used in conjunction with the
SELECT statement. ASC denotes ascending order,
while DESC denotes descending order.

@the_master_graduates
D A I L Y S Q L

What is the difference between order and group


by?

The GROUP BY clause is used in SQL queries to organize


data that have the same attribute values. Usually, we
use it with the SELECT statement. It is important to
remember that we have to place the GROUP BY clause
after the WHERE clause. Additionally, it is paced before
the ORDER BY clause. We can often use this clause in
collaboration with aggregate functions like SUM, AVG,
MIN, MAX, and COUNT to produce summary reports from
the database. It's important to remember that the
attribute in this clause must appear in the SELECT
clause, not under an aggregate function. If we do so, the
query would be incorrect. As a result, the GROUP BY
clause is always used in conjunction with the SELECT
clause. The query for the GROUP BY clause is grouped
query, and it returns a single row for each grouped
object.

@the_master_graduates
D A I L Y S Q L

Write an SQL query to fetch employee names


having a salary greater than or equal to 20000
and less than or equal to 10000.

By using BETWEEN in the where clause, we can


retrieve the Employee Ids of employees with salary
>= 20000 and <=10000.

Example:
SELECT FullName
FROM EmployeeDetails
WHERE EmpId
IN (SELECT EmpId FROM EmployeeSalary WHERE
Salary
BETWEEN 0 AND 10000);

@the_master_graduates
D A I L Y S Q L

What is SQL injection? When does SQL injection


occur?

SQL Injection is a type of database attack


technique where malicious SQL statements are
inserted into an entry field of database in a way
that once it is executed, the database is exposed
to an attacker for the attack. This technique is
usually used for attacking data-driven applications
to have access to sensitive data and perform
administrative tasks on databases.

@the_master_graduates
D A I L Y S Q L

What is ENUM?

An ENUM is a string object with a value chosen


from a list of permitted values that are
enumerated explicitly in the column specification
at table creation time.

@the_master_graduates
D A I L Y S Q L

What is the difference between the ATAN and


ATAN2 function?

ATAN() function in MySQL is used to return the


arc tangent of any number x. The arctangent of
x is defined as the inverse tangent function of x
when x is real (x ℝ).

ATAN2() function in MySQL is used for returning


the arc tangent between specified two
numbers, i.e., x and y. It returns the angle
between the positive x-axis and the line from
the origin to the point (y, x).

@the_master_graduates
D A I L Y S Q L

What is the difference between the CEIL, FLOOR


and ROUND functions?

ROUND - Rounds a positive or negative value to


a specific length.

CEILING - Evaluates the value on the right side


of the decimal and returns the smallest integer
greater than, or equal to, the specified numeric
expression.

FLOOR - Evaluates the value on the right side of


the decimal and returns the largest integer less
than or equal to the specified numeric
expression.

@the_master_graduates
D A I L Y S Q L

What is the RAND() function?

The RAND() function will return a value between 0


(inclusive) and 1 (exclusive). The RAND() function
will return a completely random number if no seed
is provided, and a repeatable sequence of random
numbers if a seed value is used.

@the_master_graduates
D A I L Y S Q L

What is the difference between LOCALTIMESTAMP


and CURRENT_TIMESTAMP?

LOCALTIMESTAMP returns only time stamp value


where as the function CURRENT_TIMESTAMP will
return time stamp with Time Zone value.

@the_master_graduates
D A I L Y S Q L

Name three functions that specify current date


and time.

SQL Server provides several different functions


that return the current date time including:
GETDATE(), SYSDATETIME(), and
CURRENT_TIMESTAMP.

@the_master_graduates
D A I L Y S Q L

Which function returns the difference between


two periods? What would the format of the
output be?

DATEDIFF() is a basic SQL Server function that can


be used to do date math. Specifically, it gets the
difference between 2 dates with the results
returned in date units specified as years, months,
days, minutes, seconds as an int (integer) value.

@the_master_graduates
D A I L Y S Q L

How can we fetch common records from two


tables?

Intersection A B of two sets A and B is the set,


which contains all the elements of A, which also
belong to B (or equivalently, all elements of B that
also belong to A), but no other elements.

Let A={ Orange, pineapple, banana} and let B={


spoon, Orange, pineapple, mango}
A B = {Orange, pineapple}
Select * from student
Select * from student1
(Select * from student) Intersect (Select * from
student1)

@the_master_graduates
D A I L Y S Q L

How can we 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 row no, employeeId from
employee) where mod(row no,2)=0

To display odd numbers Select employeeId from


(Select rowno, employeeId from employee)
where mod(row no,2)=1

@the_master_graduates
D A I L Y S Q L

How can we select unique records from a table?

Select unique records from a table by using the


DISTINCT keyword.

@the_master_graduates
D A I L Y S Q L

What is the command used to fetch the first 5


characters of the string?

SELECT SUBSTRING ('Master Graduates', 1, 5) AS


ExtractString;

@the_master_graduates
D A I L Y S Q L

How to use LIKE in SQL?

The LIKE operator checks if an attribute value


matches a given string pattern. Here is an example
of LIKE operator:

SELECT *
FROM employees
WHERE first_name like ‘Master’;

With this command, we will be able to extract all


the records where the first name is like “Master”.

@the_master_graduates
D A I L Y S Q L

How can we copy a table in SQL?

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.

Example:
SELECT *
INTO newtable
FROM oldtable
WHERE condition;

If we want to copy only some specific columns, we can do it


this way:

SELECT column1, column2, column3, ...


INTO newtable
FROM oldtable
WHERE condition;

@the_master_graduates
D A I L Y S Q L

If we drop a table, does it also drop related


objects such as constraints, indexes, columns,
default, views and sorted procedures?

Yes, SQL server drops all related objects, which


exists inside a table like constraints, index,
columns, defaults etc. However, dropping a table
will not drop views and sorted procedures as they
exist outside the table.

@the_master_graduates
D A I L Y S Q L

What is Live Lock?

A live lock is one wherein a request for an


exclusive lock is repeatedly denied because a
series of overlapping shared locks keep
interfering.

@the_master_graduates
D A I L Y S Q L

Can you join a table by itself?

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.

@the_master_graduates
D A I L Y S Q L

Explain Equi join with an example.

When two or more tables has been joined using


equal to operator then this category is called as
equi join.

Example:
SELECT a.Employee_name, b.Department_name
FROM Employee a, Employee b
WHERE a.Department_ID = b.Department_ID

@the_master_graduates
D A I L Y S Q L

Explain non-Equi join with an example.

When two or more tables are joining without an


equal to condition then that join is known as Non
Equi Join. Any operator can be used here, that is
<>,!=,<,>,Between.

Example:
SELECT b.Department_ID, b.Department_name
FROM Employee a, Department b
WHERE a.Department_id <> b.Department_ID;

@the_master_graduates
D A I L Y S Q L

State the difference between NVL and NVL2


functions.

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. With the
NVL2(exp1, exp2, exp3) function, if exp1 is not null,
then exp2 is returned; otherwise, the value of exp3
is returned.

@the_master_graduates
D A I L Y S Q L

Where is MyISAM table stored?

Each MyISAM table is stored on disk in three files.


The “.frm” file stores the table definition.
The data file has a ‘.MYD’ (MYData) extension.
The index file has a ‘.MYI’ (MYIndex) extension.

@the_master_graduates
D A I L Y S Q L

What does myisamchk do?

It compresses the MyISAM tables, which reduces


their disk or memory usage.

How can we store videos inside SQL server table?

By using FILESTREAM datatype, which was


introduced in SQL Server 2008.

@the_master_graduates
D A I L Y S Q L

Write an SQL query to show the second highest


salary from a table.

Below is the syntax to find 2nd highest salary in


SQL:

SELECT name, MAX(salary)


FROM employees
WHERE salary < (SELECT MAX(salary)
FROM employees);

@the_master_graduates
D A I L Y S Q L

How would you select all the users whose phone


number is NULL?

SELECT user_name
FROM users
WHERE ISNULL(user_phonenumber);

@the_master_graduates
D A I L Y S Q L

Write an SQL query to fetch three max salaries


from a table.

SELECT TOP 1 salary


FROM ( SELECT TOP 3 salary FROM
employee_table ORDER BY salary DESC ) AS emp
ORDER BY salary ASC;

@the_master_graduates
D A I L Y S Q L

What does a BCP command do?

The Bulk Copy is a utility or a tool that


exports/imports data from a table into a file and
vice versa.

Can a view be active if the base table is dropped?

No, the view cannot be active if the parent table is


dropped.

@the_master_graduates
D A I L Y S Q L

When should we use NoSQL and SQL?

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.

@the_master_graduates
D A I L Y S Q L

What is SYSTEM privilege?

Rights are given to a user, usually by the DBA, to


perform a particular action on the database
schema objects like creating tablespaces.

The following are examples of system privileges


that can be granted to users:

CREATE TABLE allows a grantee to create tables


in the grantee's schema.
CREATE USER allows a grantee to create users in
the database.
CREATE SESSION allows a grantee to connect to
an Oracle database to create a user session.

@the_master_graduates
D A I L Y S Q L

What are object privileges?

An object-level privilege is a permission granted to


a database user account or role to perform some
action on a database object. These object
privileges include SELECT, INSERT, UPDATE,
DELETE, ALTER, INDEX on tables, and so on.

The following example is of object privileges that


can be granted to users:

SELECT ON hr.employees TO myuser INSERT ON


hr.employees TO myuser

@the_master_graduates
D A I L Y S Q L

Does the data stored in the stored procedure


increase access time or execution time?

Data stored in stored procedures can be retrieved


much faster than the data stored in the SQL
database. Data can be precompiled and stored in
stored procedures. This reduces the time gap
between query and compiling as the data has been
pre-compiled and stored in the procedure.

@the_master_graduates
D A I L Y S Q L

What is CTE?

A CTE or common table expression is an expression


that contains temporary result set which is
defined in a SQL statement.

Does view contain data?

No, Views are virtual structures.

Define a temp table.

A temp table is a temporary storage structure to


store the data temporarily.

@the_master_graduates
D A I L Y S Q L

What is the difference between the RANK() and


DENSE_RANK() function?

The only difference between the RANK() and DENSE_RANK()


functions is in cases where there is a “tie”;

i.e., in cases where multiple values in a set have the same


ranking. In such cases, RANK() will assign nonconsecutive
“ranks” to the values in the set (resulting in gaps between
the integer ranking values when there is a tie), whereas
DENSE_RANK() will assign consecutive ranks to the values
in the set (so there will be no gaps between the integer
ranking values in the case of a tie).

For example, consider the set {25, 25, 50, 75, 75, 100}. For
such a set, RANK() will return {1, 1, 3, 4, 4, 6} (note that the
values 2 and 5 are skipped), whereas DENSE_RANK()
will return {1,1,2,3,3,4}.

@the_master_graduates
D A I L Y S Q L

What is referential integrity?

Set of rules that restrict the values of one or more


columns of the tables based on the values of the
primary key or unique key of the referenced table.

@the_master_graduates
D A I L Y S Q L

What does query optimization imply?

Query optimization is a process in which a


database system compares different query
strategies and selects the query with the least
cost.

@the_master_graduates
D A I L Y S Q L

What are nested triggers?

Triggers may implement data modification logic by


using INSERT, UPDATE, and DELETE statements.
These triggers that contain data modification logic
and find other triggers for data modification are
called Nested Triggers.

@the_master_graduates
D A I L Y S Q L

What is schema in SQL server?

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_master_graduates
D A I L Y S Q L

Write a query to fetch 50% records from an


EmployeeInfo table.

SELECT TOP 50 PERCENT *


FROM Employee;

Write a query to add email validation to your


database.

SELECT * FROM student


WHERE s_email LIKE '%@gmail.com';

@the_master_graduates

You might also like