MS SQL

In this blog we will learn about 
  • SQL database
  • create database
  • create table
  • insert and update data
  • delete data and table
  • create stored procedure
  • select data
  • group data by group by clause
  • sort data with ORDER BY clause
  • Joining data from multiple table
  • aggregating data with aggregate function
Data is simply information about something that include text, numbers , date, sounds, pictures, video etc.

Database is a collection of related data stored electronically in a systematic manner
simply its the collection of related data
database is stored electronically in computer system



DBMS stands for database management system
It is simply the system to manage data

this like 
  1. insert data
  2. update data
  3. delete data
  4. manage access 
are done by DBMS






What is SQL?
  • SQL stands for Structured query language. Its aka sequel.
  • standard language to access database
  • is an ANSI standards(American National Standards Institute)
  • can retrieve data from database
  • can create database
  • can create table
  • can create view
in 1970 EF codd gave the theory of SQL to access data base using relation algebra and TRC(tuple Relation calculus)
he gave theory that we can we can store and fetch the data

IBM started implementing  this

SEQUEL means simple English query language

Domain specific language

declarative language(what to do it don't care how to do)

DDL(data defination language)
create 
Alter
drop

DML(Data manipulation language)
insert
update
delete

DCL(Data control language)
grant revoke

What is T-SQL? what can it do?

T-SQL stands for Transact SQL. Microsoft version of SQL is T-SQL

to be compliant with ANSI standard all vendor implementation of SQL must support major commands the same way.
such commands are
  • SELECT
  • UPDATE
  • DELETE
  • INSERT
  • WHERE
T-SQL is a declarative language means it describe what it requires but now how to get it

T-SQL tells the database engine what it wants and the database engine handles the processing.
its microsoft's dialect
it implements ANSI but also adds it's own extension to SQL

TSQL can do following:
  • execute queries against a database
  • get data from database
  • add records into a database
  • update records into a database
  • remove records from a database
  • create new database and table and views
  • create stored procedures
  • set permissions on database objects


What is SQL server?
  • Microsoft SQL server is a relational database system(RDMS) developed by Microsoft
  • used to store and retrieve data requested by application
  • runs mainly on windows environment but now runs on Linux environment too
  • SQL server can be installed as a remote server or locally on your computer
  • An SQL server installation is called an instance. Multiple instance can be installed on same machine
  • SQL is used to interact with RDMS
  • Microsoft has its own implementation of SQL called Transact SQL
Hardware Requirements

software requirements

SQL Server Edition


download sql server from 
https://www.microsoft.com/en-us/sql-server/sql-server-downloads


named instance: SQLSERVER2019

What is SQL server management studio -SSMS?
  • SQL server management studio is an integrated development environment(IDE) that provides a graphical interface for connecting and working with MS SQL Server
  • It is a free tool provided by Microsoft to manage SQL Servers
  • Used by professionals like database administrators and developers
  • used to access , configure, manage, administer and develop all components of SQL server
After you download sql server we can download and install SSMS


Basic Database concept

Database is organized collection of data

Table is a collection of related data entries and it consists of column and rows

Column is set of data values in a table

Row is a record in a table

Schema is a collection of database objects

Primary Key is a unique identifier such as a driver license number

Foreign Key is used to reference a primary key in another table

Relational Database is database with related tables

Relational Database management system RDMS is a software that manages database e.g. Oracle Microsoft SQL Server, MySQL



SQL TOP

SELECT  TOP  NUMBER(INTEGER)  FROM  TABLE_NAME;
TOP statement is used to display the specific number of rows from the table



GO Command
Go is a command recognized by the SSMS and is not a T-SQL statements
GO is command used as a signal to perform a task
GO command can not occupy the same line as a T-SQL statement
GO command requires no permission for it to be used 
It simply indicate go ahead nothing more
first GO indicates beginning of query and GO at last indicates end of statement



USE Command
USE command is used to change the database context to a specified database


A schema is a container that includes a set of objects like tables, views etc. Schema's are restricted by permissions. A permission to a schema will also give access to set of objects inside it

For USE command to work you must have permission to connect to the database


SQL DISTINCT AND TOP

DISTINCT is simple used to return the distinct record or it is simply used return unique value
we can also used top with distinct 

CURD Create Read Update and Delete


to create database we use create statement
CREATE DATABASE dbname;
dbname must be unique within your sql server instance and must have maximum of 128 characters

to create table we use create statement
use dbname
GO
CREATE TABLE schema.table_name
(
table_field datatype constrains
)
GO


The GO keyword separates statements when more than one statement is submitted in a single batch.
GO is optional when the batch contains only one statements



An SQL Script is a set of SQL commands saved as a file with .sql extension. A script can contain one or more SQL statements


Create commands

Create command is used to create a new database or new table in database

to create database

CREATE DATABASE dbname;


to create table
use dbname;
go
create table schema.tblname
(
field_name datatype constrain 
)
go

go separate statements when more than one statement is submitted in a single batch.
GO is optional when the batch contains only one statement


Here dbo stands for database owner
dbo is default schema



inserting data into table


INSERT INTO schema.tblname (field name)
values
(values),
(values)
GO

The database schema is its structure described in a formal language supported by the database management system. The term "schema" refers to the organization of data as a blueprint of how the database is constructed

Reading data from table

we use select statements to read the data from database

select columns name from table_name
we can use * for selecting all the data from table name

comments are exclude 
we can comment by /*     */
every thing inside  /*     */ are comment all text or quires are excluded 
-- is used as single line comment
comments are just to describe what going on

we can also use where using different condition

where clause is used to limit rows(records) returned by the query to the users


views
  • view is a virtual table that is based on the results set of an SQL statements
  • view are stored select statements that can be queried like tables
  • views can consists of one or more table
  • Data in a view is usually or always up to date
use yourdb
CREATE VIEW view_name
as
select column from view_name
go


views as just like table so we can treat and run query to view like table but we cannot use update or insert statement in views]


Updating data from a table using T-SQL

update table_name
set columnname = 'Flat head screwdriver'
where othercolumnname=2
go


be careful when using updating records in table
notice the WHERE clause in the UPDATE statement.
The WHERE clause specifies which records(s) that should be updated.
if you omit the WHERE clause all the records in the table will be updated


Deleting records from database using T-SQL

DELETE FROM table_name WHERE column = table_data

there WHERE clause specifies which records(s) should be deleted.
if you omit WHERE clause all the records in the table will be deleted.

Truncate Database table

means removing all the data from the table

TRUNCATE TABLE table_name



Stored Procedures

  • stored procedure is one or more transact-SQL statements that executes as a batch
  • stored procedures can have both input and output parameters
  • they can contain statements to control the flow of the code
  • It's Good practice in programming to used stored procedures for repetitive task in the database

CREATE PROCEDURE pr_name @var datatype
AS
BEGIN
--the print statements returns text to the user
--cast function is used for type casting
PRINT 'Products less than ' + CAST(@var AS varchar(10));
-- A second statements starts here statements are aka branch
SELECT columnname FORM table_name 
WHERE column_name <var;
END
GO

we can view stored procedure going inside database inside programmability and inside stored Procedures

to execute 
EXECUTE pr_name 10.00;
GO


Dropping Database Table 

Dropping a table basically means deleting the table from your database.
Always make sure the table you are dropping is not being referenced by other table in your database

DROP TABLE table_name;
GO


Dropping Database

Dropping database means deleting a database.
This will delete all information stored inside that database including any tables


DROP DATABASE database_name
GO

note: we cannot drop the database if the data base is active or database are in use

Backup database

there are many types of back up

Full backup

Its always good idea to back up a database
Always back up the database to a different drive than the actual database
so that even if you get a disk crash you will not lose your backup file along with the database



BACKUP DATABASE database_name
TO DISK = "path/name.bak"
GO

Restore Database

RESTORE DATABASE database_name
FROM DISK = "path\dbname.bak"
GO

.bak basically means backup file


Filtering Records
Records are aka Rows
We will be using WHERE CLAUSE
  • Basic equality filters
  • Basic Comparisons
  • Logical comparisons
  • String comparisons
  • NULL comparison
Filtering data using equality filters
  • Equals to =
  • Not equals to <>
  • Less than or equal to <=
  • Greater than or equal to >=
--USING EUALITY

SELECT COLUMN 
FROM TABLENAME 
WHERE column = 'XYZ';
GO


INSTEAD OF = WE CAN ALSO USE <> (NOT EQUAL TO), <= (Less than or equal to),OR >=(greater than or equal to)


FILTERING RECORDS USING LOGICAL COMPARISON

  • OR
  • AND
  • IN
  • BETWEEN
We can use all this logical comparison operator with WHERE Clause

SELECT COLUMN 
FROM TABLENAME 
WHERE column = 'XYZ'
OR
COLUMMN='ABC';
GO

OR return based on column='xyz' or column ='abc'
if any condition is true than it will select or display value

we can use AND instead of OR
if will display rows which satisfy both condition



IN comparison is also compression operator
SELECT COLUMN 
FROM TABLENAME 
WHERE col IN ('xyz','abc');
GO

it will only display with the col name xyz and abc


BETWEEN  Comparison operator

SELECT COLUMN 
FROM TABLENAME 
WHERE col BETWEEN 1 to 10;
GO

it will only display rows if col is between 1 to 10

Filtering records using String comparison
  • Like operator
  • Not Like operator
  • Wild cards(%) (_)



SELECT COLUMN 
FROM TABLENAME 
WHERE col LIKE  '%XYZ%';
GO

above statement display rows with col name with name xyz

LIKE is used to search the pattern with xyz name


with LIKE clause we must use wildcard (%,_)


% substitute 0 or more characters

__ substitute single character



Sorting returned records


order by clause

used to sort records returned by TSQL query
placed last in query




sort by ascending
SELECT column 
FROM table_name
ORDER BY column name ASC;

sort by descending 
SELECT column 
FROM table_name
ORDER BY column name DSC;


sort by multiple columns

SELECT column 
FROM table_name
ORDER BY column name1, column name 2 DSC;


Table Joins
What is Joins?


Why join tables?
to combine rows from two or more related table and presented as one output result


Inner Join

Inner Join is used to select rows from tables where participating tables have identical columns

SELECT a.col1name , b.col2name FROM tbl1name a INNER JOIN tbl2name b ON a.pk = b.pk

Aliases names are used to give a table a temporary name to simplify the T-SQL query.
They define in the FORM part of the query

Inner Join must have columns that match





Left outer Join

In left outer join  all the rows from the left table are returned regardless  if there is a match from the outer table. The outer table will return NULL value where there is no match with left table


SELECT a.col , other required cols, b.col 
FROM tbl1 a LEFT OUTER JOIN tbl2 b 
ON a.pk=b.pk






Right outer join
Right outer join keyword is used to return all the rows from the right table regardless if there is any matching rows from the left table. LEFT table displays null values if there is no match found

the right table is specified in the right join part of the t-sql query

SELECT a.col, b.col FROM tbl1 a RIGHT OUTER JOIN tbl2 b ON  a.pk=b.pk








Full join





Aggregate function

aggregate function are used to calculate values in a t-sql query and returns a single result value


COUNT() returns number of rows

SELECT COUNT(COL NAME) FROM TABLE NAME

AVG() returns the average value


MAX() returns the largest value
MIN() returns the smallest value
SUM() returns the sum


Normalization
The process of converting a complex database structure into simple and more reliable database structure is called normalization

simply it is a technique of organizing the data into multiple tables to minimize data redundancy

Data redundancy is repetition of data , data redundancy increases the data base size
no only this much there will be the issues like insertion problems, deletion problem, updation problem and much more



  1. The process works through different stages Known as 'normal Forms;
  2. These stage are 1F,2F,3NF,BNCF and so on
  3. Each stage or normal form has certain rules and requirements or conditions
  4. if a relation is satisfied the conditions of a normal for , it is said to be in the normal form
Types of normalization 
  1. 1NF
  2. 2NF
  3. 3NF
  4. BCND- BOYCE CODD NORMAL FORM
  5. 4NF
  6. 5NF
First normal Form

a relation or table in first normal form if it does not contain 'repeating groups' The value in each attribute should be atomic and every tuple should be unique. Each cell in a relation should contain only one value.

A set of one or more data items that may occur a variable number of times in a tuple is called Repeating groups.

steps of 1N
  • Scalable table design which can be easily extended 
  • If your table is not even in first normal form its considered poor DB design
Every table in you database should at least follow the 1st normal form or stop using database

also it is the step 1 to move to higher normal form


How to achieve 1st normal form?
There are 4 basic rules that a table should follow to be in first normal form


rule 1
  • each column should contain atomic values
rule 2
  • A column should contain values that are of the same type
  • don't intermix different types of values in any column
rule 3
  •  Each column should have a unique name
  • same name leads to confusion at the time of data retrieval
Rule 4
  • Order in which data is saved doesn't matter
  • using SQL query, you can easily fetch data in any order from a table

2nd Normal Form
2 conditions should be stratified for 2nd normal form
  1. It should be in the first normal form
  2. And its should not have any partial dependencies 
What is partial dependencies?

column with no sense should not included in table 
it is recommend to use auto increment primary key
a=  >b

a is prime attributes
b is not prime attributes

b depends on a



3rd Normal Form
2 conditions should be stratified for 3rd normal form
  1. It should be in the second normal form
  2. And its should not have any Transitive dependencies 

in simple words a is non prime attribute and b is prime attribute

Boyce Codd Normal Form(BCNF)
2 conditions for BCNF 
  1. it should be in 3rd normal form
  2. for any dependency A => B, A should be a super Key
which means for A => B 
if A should be super key


4th Normal FORM

  • It should satisfy  BCNF
  • It should not have Multivalued Dependency
A == > B is multivalued Dependency
if for single value of A more than one value of B exists 

A table should have at least 3 columns to have multivalued dependency

because if there was only 2 column we can simply distribute table in multiple rows

B and C should be independent of each other



5th Normal form
conditions
  • should be in 4 NF
  • it should not have Join Dependency
  • aka PJNF Project join Normal Form
  • if join dependency exist decompose the table




What are DBMS keys?
DBMS key is an attribute or a set of attributes which help you uniquely identify a record or a row of data in relation(table)

Why we need DBMS Keys?
  • for identifying any row of data in table uniquely
  • we can force identity of data and ensure integrity of data is maintained
  • to establish relationship between tables and identifying relationship between table
Types of DBMS keys
  1. Super key
  2. candidate key
  3. primary key
  4. Foreign key
  5. composite and compound key
  6. Alternate key
  7. Surrogate Key

Super key
  • It is nothing but a key which we just understood in the beginning
  • An attribute or a set of attribute that can be used to identify row of data in a table is super key
Candidate key
  • It is nothing but minimal subset of super key
  • if any proper subset of a super kay is a super key than that key cannot by candidate key
Primary key 
  •  the candidate key chosen to uniquely identify each row of data in a table
  • no two rows can have the same primary key value , primary key value cannot be NULL and every row must have primary key
Foreign key
  • It is an attribute in a table which is used to define its relationship with another table
  • using foreign key helps in maintaining data integrity for table in relationship
Data Model is diagram that displays set of table and relation between them. It is easily understood.

Stages of Data Model
  1. Conceptual Data Model
  2. Logical Data Model
  3. Physical Data Model

conceptual Data model

is just a set of square set connected by lines
set of square set represents entities
and line represent relationship between entities 
can be made on white board or paper
Highly abstract
Easily Understood even for non technical people
easily enhanced
Only "entities" visible
Abstract Relationships
Nor software tool is required to define conceptual data model

once conceptual data model is finalize we can now make logical data model


Logical Data model

expands conceptual data model by adding more detail to it
Presence of Attributes(more columns) of each entity
these attributes are further identified as key attributes and non key attributes
key attributes is unique
there is a line in logical data model
all the attribute above the line is a key attribute
primary key - foreign key relation is clearly define
User Friendly Attribute names
More detail than conceptual model
database agnostic
bit more effort required to enhance in comparison to conceptual model
by using different data modeling tool like ERWIN or PowerDesigner we can easily and automatically convert logical data to physical data model



Physical Data Model
Entities referred to as tables
attributes referred to as columns
database compatible table name and column name
database specific data types
difficult for users to understand
significantly more effort required to enhance in comparison to logical model
will include indexes, constraints, triggers and other DB objects






Instances 
At any instant of time the content of the database is called the instance of database
the data in a database at a particular moment is called database state
Database states are also called current set of occurrences or instances
every time we insert or delete  a record or change the value o data item in a record we change one state of the database into another

 
Schema (logical representation)3
logical description of the program is algorithms
logical description of database is known as schema

the description of database is called database schema which is specified during database design and not expected to change frequently

most of the time data models have certain convention for displaying schema as diagram

Problem with the schema diagram is that it doesn't represent all the aspect of schema diagram neither the data types nor the relations of files with each other




types
physical schema: Describes the database design at physical level
logical schema: Describes the database design at logical level



SQL QUERIES

Emp

E_id

E__name

Dept

Salary

1

Ram

Hr

10000

2

Amrit

Mrkt

20000

3

ravi

Hr

30000

4

Nitin

Mrkt

40000

5

Varun

IT

50000


SQL QUERY to display maximum salary from employee table

SELECT MAX(salary) from emp

write a SQL query to display employee name who is taking a maximum salary


SELECT e__name from emp where
salary=(SELECT MAX(salary) FROM emp )




SELECT e__name from emp where this is outer query


SELECT MAX(salary) FROM emp this is inner query




write SQL query to display second highest salary from employee table

SELECT MAX(salary) FROM emp WHERE salary <> (SELECT MAX(salary) FROM emp)



write a SQL query to display employee name who is taking a second maximum salary
SELECT  e_name FROM  emp WHERE salary =(SELECT MAX(salary) FROM emp WHERE salary <> (SELECT MAX(salary) FROM emp))



Write a query to display all the dept along with the number of employee working?

HR

2

Mrkt

2

IT

1


SELECT  dept,count(*)   FROM emp GROUP BY dept


write a query to display all the dept name  with number of emps are less than 2

SELECT  dept FROM emp GROUP BY dept HAVING COUNT(*)<2



Write the query to display highest salary department wise and name of employee who is taking the salary

emp

E_id

E__name

Dept

Salary

1

Ram

Hr

10000

2

Amrit

Mrkt

20000

3

ravi

Hr

30000

4

Nitin

Mrkt

40000

5

Varun

IT

50000



select dept, max(salary) from emp group by dept



select e_name from emp where salary in (
select max(salary) from emp group by dept) 


IN / NOT IN
detail of emp whose address is either ktm, lalit, bkt

select * from emp where address in ( 'ktm','lalit','bkt')


find the  name of employee who are working on a project

emp table
eid,ename, address

project
eid,pid,pname,location


select emame from emp where eid in
(select eid from project)









Set difference
(A-B)
Contain value of A but not B
A intersection not B
Rules
  • Number of column must be same
  • Domain or data of every table must be same




Union
A Union B
Rules
  • Number of column must be same
  • Domain or data of every table must be same
Division operator
it is derived operator

A(x,y) / B(y)===== It results x values for that there should be tuple <x,y> for every y value of relation


Deferred database modification(log based recovery)

a=100
b=200
a=a+100
w(a)
r(b)
b=b+200
w(b)
commit


roll back

new value is stored
it is called not undo redo


Immediate database modification(log based recovery)
does not wait for commit
undo/redo strategies


relationship

one to one


association between two relation / tables
1-1
1-m
m-1
m-m

1 to 1 
2 table are connected
eg one employee in one department
 both employee and department cannot be repeated




What is the difference between SQL and MySQL?

SQL vs MySQL

SQLMySQL
SQL is a standard language which stands for Structured Query Language based on the English languageMySQL is a database management system.
SQL is the core of the relational database which is used for accessing and managing database

MySQL is an RDMS (Relational Database Management System) such as SQL Server, Informix etc.

What are the different subsets of SQL?

  • Data Definition Language (DDL) – It allows you to perform various operations on the database such as CREATE, ALTER, and DELETE objects.
  • Data Manipulation Language(DML) – It allows you to access and manipulate data. It helps you to insert, update, delete and retrieve data from the database.
  • Data Control Language(DCL) – It allows you to control access to the database. Example – Grant, Revoke access permissions.

 What do you mean by DBMS? What are its different types?

Database - SQL Interview Questions - EdurekaDatabase Management System (DBMS) is a  software application that interacts with the user, applications, and the database itself to capture and analyze data. A database is a structured collection of data. 

A DBMS allows a user to interact with the database. The data stored in the database can be modified, retrieved and deleted and can be of any type like strings, numbers, images, etc.

There are two types of DBMS:

  • Relational Database Management System: The data is stored in relations (tables). Example – MySQL.
  • Non-Relational Database Management System: There is no concept of relations, tuples and attributes.  Example – MongoDB


What is RDBMS? How is it different from DBMS?

A relational database management system (RDBMS) is a set of applications and features that allow IT professionals and others to develop, edit, administer, and interact with relational databases. Most commercial relational database management systems use Structured Query Language (SQL) to access the database, which is stored in the form of tables.
The RDBMS is the most widely used database system in businesses all over the world. It offers a stable means of storing and retrieving massive amounts of data.

Databases, in general, hold collections of data that may be accessed and used in other applications. The development, administration, and use of database platforms are all supported by a database management system.

A relational database management system (RDBMS) is a type of database management system (DBMS) that stores data in a row-based table structure that links related data components. An RDBMS contains functions that ensure the data’s security, accuracy, integrity, and consistency. This is not the same as the file storage utilized by a database management system.

The following are some further distinctions between database management systems and relational database management systems:

The number of users who are permitted to utilise the system
A DBMS can only handle one user at a time, whereas an RDBMS can handle numerous users.
Hardware and software specifications
In comparison to an RDBMS, a DBMS requires fewer software and hardware.
Amount of information
RDBMSes can handle any quantity of data, from tiny to enormous, whereas DBMSes are limited to small amounts.
The structure of the database
Data is stored in a hierarchical format in a DBMS, whereas an RDBMS uses a table with headers that serve as column names and rows that hold the associated values.
Implementation of the ACID principle
The atomicity, consistency, isolation, and durability (ACID) concept is not used by DBMSs for data storage. RDBMSes, on the other hand, use the ACID model to organize their data and assure consistency.
Databases that are distributed
A DBMS will not provide complete support for distributed databases, whereas an RDBMS will.
Programs that are managed
A DBMS focuses on keeping databases that are present within the computer network and system hard discs, whereas an RDBMS helps manage relationships between its incorporated tables of data.
Normalization of databases is supported
A RDBMS can be normalized , but a DBMS cannot be normalized.


What is a Self-Join?

A self-join is a type of join that can be used to connect two tables. As a result, it is a unary relationship. Each row of the table is attached to itself and all other rows of the same table in a self-join. As a result, a self-join is mostly used to combine and compare rows from the same database table.

Why do we  nedd self join






if we want to find name of people living from rahaul's city in such case we use self join

 


Join= cross product + conditions

find student id who is enrolled in at least two courses

s_id    c_id    scince

s1        c1        2016

s2        c2        2017

s1        c2        2017

SELECT t1.s_id FROM  study as t1 , study as t2 WERE t1.sid=t2.sid AND t1.cid<>t2.c_id


 What is the SELECT statement?

A SELECT command gets zero or more rows from one or more database tables or views. The most frequent data manipulation language (DML) command is SELECT in most applications. SELECT queries define a result set, but not how to calculate it, because SQL is a declarative programming language.


What are some common clauses used with SELECT query in SQL?

The following are some frequent SQL clauses used in conjunction with a SELECT query:

WHERE clause: In SQL, the WHERE clause is used to filter records that are required depending on certain criteria.
ORDER BY clause: The ORDER BY clause in SQL is used to sort data in ascending (ASC) or descending (DESC) order depending on specified field(s) (DESC).
GROUP BY clause: GROUP BY clause in SQL is used to group entries with identical data and may be used with aggregation methods to obtain summarised database results.
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.


The following table shows the comparisons between these two clauses, but the main difference is that the WHERE clause uses condition for filtering records before any groupings are made, while HAVING clause uses condition for filtering values from a group.

HAVINGWHERE
1. The HAVING clause is used in database systems to fetch the data/values from the groups according to the given condition.1. The WHERE clause is used in database systems to fetch the data/values from the tables according to the given condition.
2. The HAVING clause is always executed with the GROUP BY clause.2. The WHERE clause can be executed without the GROUP BY clause.
3. The HAVING clause can include SQL aggregate functions in a query or statement.3. We cannot use the SQL aggregate function with WHERE clause in statements.
4. We can only use SELECT statement with HAVING clause for filtering the records.4. Whereas, we can easily use WHERE clause with UPDATE, DELETE, and SELECT statements.
5. The HAVING clause is used in SQL queries after the GROUP BY clause.5. The WHERE clause is always used before the GROUP BY clause in SQL queries.
6. We can implements this SQL clause in column operations.6. We can implements this SQL clause in row operations.
7. It is a post-filter.7. It is a pre-filter.
8. It is used to filter groups.8. It is used to filter the single record of the table.

Syntax of HAVING clause in SQL

  1. SELECT column_Name1, column_Name2, ....., column_NameN aggregate_function_name(column_Name) FROM table_name GROUP BY column_Name1 HAVING condition;  

Examples of HAVING clause in SQL

In this article, we have taken the following four different examples which will help you how to use the HAVING clause with different SQL aggregate functions:

Example 1: Let's take the following Employee table, which helps you to analyze the HAVING clause with SUM aggregate function:

Emp_IdEmp_NameEmp_SalaryEmp_City
201Abhay2000Goa
202Ankit4000Delhi
203Bheem8000Jaipur
204 Ram2000Goa
205Sumit5000Delhi

If you want to add the salary of employees for each city, you have to write the following query:

  1. SELECT SUM(Emp_Salary), Emp_City FROM Employee GROUP BY Emp_City;  

The output of the above query shows the following output:

SUM(Emp_Salary)Emp_City
4000Goa
9000Delhi
8000Jaipur

Now, suppose that you want to show those cities whose total salary of employees is more than 5000. For this case, you have to type the following query with the HAVING clause in SQL:

  1. SELECT SUM(Emp_Salary), Emp_City FROM Employee GROUP BY Emp_City HAVING SUM(Emp_Salary)>5000;  

The output of the above SQL query shows the following table in the output:

SUM(Emp_Salary)Emp_City
9000Delhi
8000Jaipur

Example 2: Let's take the following Student_details table, which helps you to analyze the HAVING clause with the COUNT aggregate function:

Roll_NoNameMarksAge
1Rithik9120
2Kapil6019
3Arun8217
4Ram9218
5Anuj5020
6Suman8818
7Sheetal5719
8Anuj6420

Suppose, you want to count the number of students from the above table according to their age. For this, you have to write the following query:

  1. SELECT COUNT(Roll_No), Age FROM Student_details GROUP BY Age ;  

The above query will show the following output:

Count(Roll_No)Age
320
219
117
218

Now, suppose that you want to show the age of those students whose roll number is more than and equals 2. For this case, you have to type the following query with the HAVING clause in SQL:

  1. SELECT COUNT(Roll_No), Age FROM Student_details GROUP BY Age HAVING COUNT(Roll_No) >= 2 ;  

The output of the above SQL query shows the following table in the output:

Count(Roll_No)Age
320
219
218

Example 3: Let's take the following Employee table, which helps you to analyze the HAVING clause with MIN and MAX aggregate function:

Emp_IDNameEmp_SalaryEmp_Dept
1001Anuj9000Finance
1002Saket4000HR
1003Raman3000Coding
1004Renu6000Coding
1005Seenu5000HR
1006Mohan10000Marketing
1007Anaya4000Coding
1008Parul8000Finance

MIN Function with HAVING Clause:

If you want to show each department and the minimum salary in each department, you have to write the following query:

  1. SELECT MIN(Emp_Salary), Emp_Dept FROM Employee GROUP BY Emp_Dept;  

The output of the above query shows the following output:

MIN(Emp_Salary)Emp_Dept
8000Finance
4000HR
3000Coding
10000Marketing

Now, suppose that you want to show only those departments whose minimum salary of employees is greater than 4000. For this case, you have to type the following query with the HAVING clause in SQL:

  1. SELECT MIN(Emp_Salary), Emp_Dept FROM Employee GROUP BY Emp_Dept HAVING MIN(Emp_Salary) > 4000 ;  

The above SQL query shows the following table in the output:

MIN(Emp_Salary)Emp_Dept
8000Finance
10000Marketing

MAX Function with HAVING Clause:

In the above employee table, if you want to list each department and the maximum salary in each department. For this, you have to write the following query:

  1. SELECT MAX(Emp_Salary), Emp_Dept FROM Employee GROUP BY Emp_Dept;  

The above query will show the following output:

MAX(Emp_Salary)Emp_Dept
9000Finance
5000HR
6000Coding
10000Marketing

Now, suppose that you want to show only those departments whose maximum salary of employees is less than 8000. For this case, you have to type the following query with the HAVING clause in SQL:

  1. SELECT MAX(Emp_Salary), Emp_Dept FROM Employee GROUP BY Emp_Dept HAVING MAX(Emp_Salary) < 8000 ;  

The output of the above SQL query shows the following table in the output:

MAX(Emp_Salary)Emp_Dept
5000HR
6000Coding

Example 4: Let's take the following Employee_Dept table, which helps you to analyze the HAVING clause with AVG aggregate function:

Emp_IDNameEmp_SalaryEmp_Dept
1001Anuj8000Finance
1002Saket4000HR
1003Raman3000Coding
1004Renu6000Coding
1005Seenu5000HR
1006Mohan10000Marketing
1007Anaya4000Coding
1008Parul6000Finance

If you want to find the average salary of employees in each department, you have to write the following query:

  1. SELECT AVG(Emp_Salary), Emp_Dept FROM Employee_Dept GROUP BY Emp_Dept;  

The above query will show the following output:

AVG(Emp_Salary)Emp_Dept
7000Finance
4500HR
6500Coding
10000Marketing

Now, suppose that you want to show those departments whose average salary is more than and equals 6500. For this case, you have to type the following query with the HAVING clause in SQL:

  1. SELECT AVG(Emp_Salary), Emp_Dept FROM Employee_Dept GROUP BY Emp_Dept HAVING AVG(Emp_Salary) > 6500 ;  

The above SQL query will show the following table in the output:

AVG(Emp_Salary)Emp_Dept
7000Finance
6500Coding
10000Marketing
 


What are UNION, MINUS and INTERSECT commands?

The UNION operator is used to combine the results of two tables while also removing duplicate entries.
The MINUS operator is used to return rows from the first query but not from the second query.
The INTERSECT operator is used to combine the results of both queries into a single row.
Before running either of the above SQL statements, certain requirements must be satisfied –
Within the clause, each SELECT query must have the same amount of columns.
The data types in the columns must also be comparable.
In each SELECT statement, the columns must be in the same order.

What is Cursor? How to use a Cursor?

After any variable declaration, DECLARE a cursor. A SELECT Statement must always be coupled with the cursor definition.

To start the result set, move the cursor over it. Before obtaining rows from the result set, the OPEN statement must be executed.

To retrieve and go to the next row in the result set, use the FETCH command.

To disable the cursor, use the CLOSE command.

Finally, use the DEALLOCATE command to remove the cursor definition and free up the resources connected with it.


List the different types of relationships in SQL.

There are different types of relations in the database:

One-to-One – This is a connection between two tables in which each record in one table corresponds to the maximum of one record in the other.

One-to-Many and Many-to-One – This is the most frequent connection, in which a record in one table is linked to several records in another.

Many-to-Many – This is used when defining a relationship that requires several instances on each sides.

Self-Referencing Relationships – When a table has to declare a connection with itself, this is the method to employ.


What is OLTP?

OLTP, or online transactional processing, allows huge groups of people to execute massive amounts of database transactions in real time, usually via the internet. A database transaction occurs when data in a database is changed, inserted, deleted, or queried.

 What are the differences between OLTP and OLAP?

OLTP stands for online transaction processing, whereas OLAP stands for online analytical processing. OLTP is an online database modification system, whereas OLAP is an online database query response system.


How to create empty tables with the same structure as another table?

To create empty tables:
Using the INTO operator to fetch the records of one table into a new table while setting a WHERE clause to false for all entries, it is possible to create empty tables with the same structure. As a result, SQL creates a new table with a duplicate structure to accept the fetched entries, but nothing is stored into the new table since the WHERE clause is active.


What is PostgreSQL?

In 1986, a team lead by Computer Science Professor Michael Stonebraker created PostgreSQL under the name Postgres. It was created to aid developers in the development of enterprise-level applications by ensuring data integrity and fault tolerance in systems. PostgreSQL is an enterprise-level, versatile, resilient, open-source, object-relational database management system that supports variable workloads and concurrent users. The international developer community has constantly backed it. PostgreSQL has achieved significant appeal among developers because to its fault-tolerant characteristics.
It’s a very reliable database management system, with more than two decades of community work to thank for its high levels of resiliency, integrity, and accuracy. Many online, mobile, geospatial, and analytics applications utilise PostgreSQL as their primary data storage or data warehouse.

What are SQL comments?

SQL Comments are used to clarify portions of SQL statements and to prevent SQL statements from being executed. Comments are quite important in many programming languages. The comments are not supported by a Microsoft Access database. As a result, the Microsoft Access database is used in the examples in Mozilla Firefox and Microsoft Edge.
Single Line Comments: It starts with two consecutive hyphens (–).
Multi-line Comments: It starts with /* and ends with */.


What is the usage of the NVL() function?

You may use the NVL function to replace null values with a default 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 alone.

This function is used in Oracle, not in SQL and MySQL. Instead of NVL() function, MySQL have IFNULL() and SQL Server have ISNULL() function.

Let’s move to the next question in this SQL Interview Questions.

Q18. Explain character-manipulation functions? Explains its different types in SQL.

Change, extract, and edit the character string using character manipulation routines. The function will do its action on the input strings and return the result when one or more characters and words are supplied into it.

The character manipulation functions in SQL are as follows:

A) CONCAT (joining two or more values): This function is used to join two or more values together. The second string is always appended to the end of the first string.

B) SUBSTR: This function returns a segment of a string from a given start point to a given endpoint.

C) LENGTH: This function returns the length of the string in numerical form, including blank spaces.

D) INSTR: This function calculates the precise numeric location of a character or word in a string.

E) LPAD: For right-justified values, it returns the padding of the left-side character value.

F) RPAD: For a left-justified value, it returns the padding of the right-side character value.

G) TRIM: This function removes all defined characters from the beginning, end, or both ends of a string. It also reduced the amount of wasted space.

H) REPLACE: This function replaces all instances of a word or a section of a string (substring) with the other string value specified.

Q19. Write the SQL query to get the third maximum salary of an employee from a table named employees.

Employee table

employee_namesalary
A24000
C34000
D55000
E75000
F21000
G40000
H50000

 

SELECT * FROM(

SELECT employee_name, salary, DENSE_RANK() 

OVER(ORDER BY salary DESC)r FROM Employee) 

WHERE r=&n;

To find 3rd highest salary set n = 3

Q20. What is the difference between the RANK() and DENSE_RANK() functions?

The RANK() function in the result set defines the rank of each row within your ordered partition. If both rows have the same rank, the next number in the ranking will be the previous rank plus a number of duplicates. If we have three records at rank 4, for example, the next level indicated is 7.

The DENSE_RANK() function assigns a distinct rank to each row within a partition based on the provided column value, with no gaps. It always indicates a ranking in order of precedence. This function will assign the same rank to the two rows if they have the same rank, with the next rank being the next consecutive number. If we have three records at rank 4, for example, the next level indicated is 5.

Q21. What are Tables and Fields?

A table is a collection of data components organized in rows and columns in a relational database. A table can also be thought of as a useful representation of relationships. The most basic form of data storage is the table. An example of an Employee table is shown below.

IDNameDepartmentSalary
1RahulSales24000
2RohiniMarketing34000
3ShyleshSales24000
4TarunAnalytics30000

 

A Record or Row is a single entry in a table. In a table, a record represents a collection of connected data. The Employee table, for example, has four records.

A table is made up of numerous records (rows), each of which can be split down into smaller units called Fields(columns). ID, Name, Department, and Salary are the four fields in the Employee table above.

Q22. What is a UNIQUE constraint?

The UNIQUE Constraint prevents identical values in a column from appearing in two records. The UNIQUE constraint guarantees that every value in a column is unique.

Q23. What is a Self-Join?

A self-join is a type of join that can be used to connect two tables. As a result, it is a unary relationship. Each row of the table is attached to itself and all other rows of the same table in a self-join. As a result, a self-join is mostly used to combine and compare rows from the same database table.

Q24. What is the SELECT statement?

A SELECT command gets zero or more rows from one or more database tables or views. The most frequent data manipulation language (DML) command is SELECT in most applications. SELECT queries define a result set, but not how to calculate it, because SQL is a declarative programming language.

Q25. What are some common clauses used with SELECT query in SQL?

The following are some frequent SQL clauses used in conjunction with a SELECT query:


WHERE clause: In SQL, the WHERE clause is used to filter records that are required depending on certain criteria.
ORDER BY clause: The ORDER BY clause in SQL is used to sort data in ascending (ASC) or descending (DESC) order depending on specified field(s) (DESC).
GROUP BY clause: GROUP BY clause in SQL is used to group entries with identical data and may be used with aggregation methods to obtain summarised database results.
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.

Q26. What are UNION, MINUS and INTERSECT commands?

The UNION operator is used to combine the results of two tables while also removing duplicate entries. 

The MINUS operator is used to return rows from the first query but not from the second query. 

The INTERSECT operator is used to combine the results of both queries into a single row.
Before running either of the above SQL statements, certain requirements must be satisfied –

Within the clause, each SELECT query must have the same amount of columns.

The data types in the columns must also be comparable.

In each SELECT statement, the columns must be in the same order.

Let’s move to the next question in this SQL Interview Questions.

Q27. What is Cursor? How to use a Cursor?

After any variable declaration, DECLARE a cursor. A SELECT Statement must always be coupled with the cursor definition.

To start the result set, move the cursor over it. Before obtaining rows from the result set, the OPEN statement must be executed.

To retrieve and go to the next row in the result set, use the FETCH command.

To disable the cursor, use the CLOSE command.

Finally, use the DEALLOCATE command to remove the cursor definition and free up the resources connected with it.

Q28. List the different types of relationships in SQL.

There are different types of relations in the database:
One-to-One – This is a connection between two tables in which each record in one table corresponds to the maximum of one record in the other.
One-to-Many and Many-to-One – This is the most frequent connection, in which a record in one table is linked to several records in another.
Many-to-Many – This is used when defining a relationship that requires several instances on each sides.
Self-Referencing Relationships – When a table has to declare a connection with itself, this is the method to employ.

Q29. What is SQL example?

SQL is a database query language that allows you to edit, remove, and request data from databases. The following statements are a few examples of SQL statements:

  • SELECT 
  • INSERT 
  • UPDATE
  • DELETE
  • CREATE DATABASE
  • ALTER DATABASE

Q30. What are basic SQL skills?

SQL skills aid data analysts in the creation, maintenance, and retrieval of data from relational databases, which divide data into columns and rows. It also enables users to efficiently retrieve, update, manipulate, insert, and alter data.

The most fundamental abilities that a SQL expert should possess are:

  1. Database Management
  2. Structuring a Database
  3. Creating SQL clauses and statements
  4. SQL System SKills like MYSQL, PostgreSQL
  5. PHP expertise is useful.
  6. Analyze SQL data
  7. Using WAMP with SQL to create a database
  8. OLAP Skills

Q31. What is schema in SQL Server?

A schema is a visual representation of the database that is logical. It builds and specifies the relationships among the database’s numerous entities. It refers to the several kinds of constraints that may be applied to a database. It also describes the various data kinds. It may also be used on Tables and Views.

Schemas come in a variety of shapes and sizes. Star schema and Snowflake schema are two of the most popular. The entities in a star schema are represented in a star form, whereas those in a snowflake schema are shown in a snowflake shape.
Any database architecture is built on the foundation of schemas.


Q32. How to create a temp table in SQL Server?

Temporary tables are created in TempDB and are erased automatically after the last connection is closed. We may use Temporary Tables to store and process interim results. When we need to store temporary data, temporary tables come in handy.

The following is the syntax for creating a Temporary Table:

CREATE TABLE #Employee (id INT, name VARCHAR(25))
INSERT INTO #Employee VALUES (01, ‘Ashish’), (02, ‘Atul’)

Let’s move to the next question in this SQL Interview Questions.


Q33. How to install SQL Server in Windows 11?

Install SQL Server Management Studio In Windows 11

Step 1: Click on SSMS, which will take you to the SQL Server Management Studio page.

Step 2: Moreover, click on the SQL Server Management Studio link and tap on Save File. 

Step 3: Save this file to your local drive and go to the folder.

Step 4: The setup window will appear, and here you can choose the location where you want to save the file.
Step 5: Click on Install.
Step 6: Close the window after the installation is complete.
Step 7: Furthermore, go back to your Start Menu and search for SQL server management studio.

Step 8: Furthermore, double-click on it, and the login page will appear once it shows up.

Step 9: You should be able to see your server name. However, if that’s not visible, click on the drop-down arrow on the server and tap on Browse.

Step 10: Choose your SQL server and click on Connect.

After that, the SQL server will connect, and Windows 11 will run good.

Q34. What is the case when in SQL Server?

The CASE statement is used to construct logic in which one column’s value is determined by the values of other columns.

At least one set of WHEN and THEN commands makes up the SQL Server CASE Statement. The condition to be tested is specified by the WHEN statement. If the WHEN condition returns TRUE, the THEN sentence explains what to do.

When none of the WHEN conditions return true, the ELSE statement is executed. The END keyword brings the CASE statement to a close.

1
2
3
4
5
6
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;

Q35. NoSQL vs SQL

In summary, the following are the five major distinctions between SQL and NoSQL:

Relational databases are SQL, while non-relational databases are NoSQL.

SQL databases have a specified schema and employ structured query language. For unstructured data, NoSQL databases use dynamic schemas.

SQL databases scale vertically, but NoSQL databases scale horizontally.

NoSQL databases are document, key-value, graph, or wide-column stores, whereas SQL databases are table-based.

SQL databases excel in multi-row transactions, while NoSQL excels at unstructured data such as documents and JSON.

 

Q36. What is the difference between NOW() and CURRENT_DATE()?
NOW() returns a constant time that indicates the time at which the statement began to execute. (Within a stored function or trigger, NOW() returns the time at which the function or triggering statement began to execute.
The simple difference between NOW() and CURRENT_DATE() is that NOW() will fetch the current date and time both in format ‘YYYY-MM_DD HH:MM:SS’ while CURRENT_DATE() will fetch the date of the current day ‘YYYY-MM_DD’.

Let’s move to the next question in this SQL Interview Questions.

Q37. What is BLOB and TEXT in MySQL?

BLOB stands for Binary Huge Objects and can be used to store binary data, whereas TEXT may be used to store a large number of strings. BLOB may be used to store binary data, which includes images, movies, audio, and applications.
BLOB values function similarly to byte strings, and they lack a character set. As a result, bytes’ numeric values are completely dependent on comparison and sorting.
    TEXT values behave similarly to a character string or a non-binary string. The comparison/sorting of TEXT is completely dependent on the character set collection.

Q38. How to remove duplicate rows in SQL?

If the SQL table has duplicate rows, the duplicate rows must be removed.

Let’s assume the following table as our dataset:

 

IDNameAge
1A21
2B23
2B23
4D22
5E25
6G26
5E25

The following SQL query removes the duplicate ids from the  table:

DELETE FROM table WHERE ID IN (
SELECT 
ID, COUNT(ID) 
FROM   table
GROUP BY  ID
HAVING 
COUNT (ID) > 1); 

Q39. How to create a stored procedure using SQL Server?

A stored procedure is a piece of prepared SQL code that you can save and reuse again and over.
So, if you have a SQL query that you create frequently, save it as a stored procedure and then call it to run it.
You may also supply parameters to a stored procedure so that it can act based on the value(s) of the parameter(s) given.

Stored Procedure Syntax

CREATE PROCEDURE procedure_name

AS

sql_statement

GO;

Execute a Stored Procedure

EXEC procedure_name;


Q40. What is Database Black Box Testing?

Black Box Testing is a software testing approach that involves testing the functions of software applications without knowing the internal code structure, implementation details, or internal routes. Black Box Testing is a type of software testing that focuses on the input and output of software applications and is totally driven by software requirements and specifications. Behavioral testing is another name for it.


Q41. What are the different types of SQL sandbox?

SQL Sandbox is a secure environment within SQL Server where untrusted programmes can be run. There are three different types of SQL sandboxes:

Safe Access Sandbox: In this environment, a user may execute SQL activities like as building stored procedures, triggers, and so on, but they can’t access the memory or create files.

Sandbox for External Access: Users can access files without having the ability to alter memory allocation.

Unsafe Access Sandbox: This contains untrustworthy code that allows a user to access memory.

Let’s move to the next question in this SQL Interview Questions.

Q42. Where MyISAM table is stored?

Prior to the introduction of MySQL 5.5 in December 2009, MyISAM was the default storage engine for MySQL relational database management system versions.  It’s based on the older ISAM code, but it comes with a lot of extra features. Each MyISAM table is split into three files on disc (if it is not partitioned). The file names start with the table name and end with an extension that indicates the file type. The table definition is stored in a.frm file, however this file is not part of the MyISAM engine; instead, it is part of the server. The data file’s suffix is.MYD (MYData). The index file’s extension is.MYI (MYIndex). If you lose your index file, you may always restore it by recreating indexes.

Q43. How to find the nth highest salary in SQL?
The most typical interview question is to find the Nth highest pay in a table. This work can be accomplished using the dense rank() function.
Employee table

employee_namesalary
A24000
C34000
D55000
E75000
F21000
G40000
H50000

 

SELECT * FROM(

SELECT employee_name, salary, DENSE_RANK() 

OVER(ORDER BY salary DESC)r FROM Employee) 

WHERE r=&n;

To find to the 2nd highest salary set n = 2

To find 3rd highest salary set n = 3 and so on.

Q44. What do you mean by table and field in SQL?

A table refers to a collection of data in an organised manner in form of rows and columns. A field refers to the number of columns in a table. For example:

Table: StudentInformation
Field: Stu Id, Stu Name, Stu Marks

Q45. What are joins in SQL?

A JOIN clause is used to combine rows from two or more tables, based on a related column between them. It is used to merge two tables or retrieve data from there. There are 4 types of joins, as you can refer to below:

Joins-SQL-interview-Questions-Edureka

  • Inner join: Inner Join in SQL is the most common type of join. It is used to return all the rows from multiple tables where the join condition is satisfied. 
  • Left Join:  Left Join in SQL is used to return all the rows from the left table but only the matching rows from the right table where the join condition is fulfilled.

  • Right Join: Right Join in SQL is used to return all the rows from the right table but only the matching rows from the left table where the join condition is fulfilled.

  • Full Join: Full join returns all the records when there is a match in any of the tables. Therefore, it returns all the rows from the left-hand side table and all the rows from the right-hand side table.

Let’s move to the next question in this SQL Interview Questions.

Q46. What is the difference between CHAR and VARCHAR2 datatype in SQL?

Both Char and Varchar2 are used for characters datatype but varchar2 is used for character strings of variable length whereas Char is used for strings of fixed length. For example, char(10) can only store 10 characters and will not be able to store a string of any other length whereas varchar2(10) can store any length i.e 6,8,2 in this variable.

Q47. What is a Primary key?

  • Table - SQL Interview Questions - EdurekaA Primary key in SQL is a column (or collection of columns) or a set of columns that uniquely identifies each row in the table.
  • Uniquely identifies a single row in the table
  • Null values not allowed

Example- In the Student table, Stu_ID is the primary key.

Q48. What are Constraints?

Constraints in SQL are used to specify the limit on the data type of the table. It can be specified while creating or altering the table statement. The sample of constraints are:

  • NOT NULL
  • CHECK
  • DEFAULT
  • UNIQUE
  • PRIMARY KEY
  • FOREIGN KEY

Q49. What is the difference between DELETE and TRUNCATE statements?

DELETE vs TRUNCATE

DELETETRUNCATE
Delete command is used to delete a row in a table.Truncate is used to delete all the rows from a table.
You can rollback data after using delete statement.You cannot rollback data.
It is a DML command.It is a DDL command.
It is slower than truncate statement.It is faster.

Q50. What is a Unique key?

  • Uniquely identifies a single row in the table.
  • Multiple values allowed per table.
  • Null values allowed.

Apart from this SQL Interview Questions blog, if you want to get trained from professionals on this technology, you can opt for structured training from edureka! 

Q51. What is a Foreign key in SQL?

  • Foreign key maintains referential integrity by enforcing a link between the data in two tables.
  • The foreign key in the child table references the primary key in the parent table.
  • The foreign key constraint prevents actions that would destroy links between the child and parent tables.

Q52. What do you mean by data integrity? 

Data Integrity defines the accuracy as well as the consistency of the data stored in a database. It also defines integrity constraints to enforce business rules on the data when it is entered into an application or a database.

Q53. What is the difference between clustered and non-clustered index in SQL?

The differences between the clustered and non clustered index in SQL are :

  1. Clustered index is used for easy retrieval of data from the database and its faster whereas reading from non clustered index is relatively slower.
  2. Clustered index alters the way records are stored in a database as it sorts out rows by the column which is set to be clustered index whereas in a non clustered index, it does not alter the way it was stored but it creates a separate object within a table which points back to the original table rows after searching.
  3. One table can only have one clustered index whereas it can have many non clustered index.

Q54. Write a SQL query to display the current date?

In SQL, there is a built-in function called GetDate() which helps to return the current timestamp/date.

Q55.What do you understand by query optimization?

The phase that identifies a plan for evaluation query which has the least estimated cost is known as query optimization.

The advantages of query optimization are as follows:

  • The output is provided faster
  • A larger number of queries can be executed in less time
  • Reduces time and space complexity

Q56. What do you mean by Denormalization?

Denormalization refers to a technique which is used to access data from higher to lower forms of a database. It helps the database managers to increase the performance of the entire infrastructure as it introduces redundancy into a table. It adds the redundant data into a table by incorporating database queries that combine data from various tables into a single table.

Q57. What are Entities and Relationships?

Entities:  A person, place, or thing in the real world about which data can be stored in a database. Tables store data that represents one type of entity. For example – A bank database has a customer table to store customer information. The customer table stores this information as a set of attributes (columns within the table) for each customer.

Relationships: Relation or links between entities that have something to do with each other. For example – The customer name is related to the customer account number and contact information, which might be in the same table. There can also be relationships between separate tables (for example, customer to accounts).

Let’s move to the next question in this SQL Interview Questions.


Q58. What is an Index?

An index refers to a performance tuning method of allowing faster retrieval of records from the table. An index creates an entry for each value and hence it will be faster to retrieve data.

Q59. Explain different types of index in SQL.

There are three types of index in SQL namely:

Unique Index:

This index does not allow the field to have duplicate values if the column is unique indexed. If a primary key is defined, a unique index can be applied automatically.

Clustered Index:

This index reorders the physical order of the table and searches based on the basis of key values. Each table can only have one clustered index.

Non-Clustered Index:

Non-Clustered Index does not alter the physical order of the table and maintains a logical order of the data. Each table can have many nonclustered indexes.

Q60. What is Normalization and what are the advantages of it?

Normalization in SQL is the process of organizing data to avoid duplication and redundancy. Some of the advantages are:

  • Better Database organization
  • More Tables with smaller rows
  • Efficient data access
  • Greater Flexibility for Queries
  • Quickly find the information
  • Easier to implement Security
  • Allows easy modification
  • Reduction of redundant and duplicate data
  • More Compact Database
  • Ensure Consistent data after modification

Apart from this SQL Interview Questions Blog, if you want to get trained from professionals on this technology, you can opt for structured training from edureka! 

Q61. What is the difference between DROP and TRUNCATE commands?

DROP command removes a table and it cannot be rolled back from the database whereas TRUNCATE command removes all the rows from the table.

Q62. Explain different types of Normalization.

There are many successive levels of normalization. These are called normal forms. Each consecutive normal form depends on the previous one.The first three normal forms are usually adequate.

Normal Forms are used in database tables to remove or decrease duplication. The following are the many forms:

First Normal Form:
When every attribute in a relation is a single-valued attribute, it is said to be in first normal form. The first normal form is broken when a relation has a composite or multi-valued property.

Second Normal Form:

A relation is in second normal form if it meets the first normal form’s requirements and does not contain any partial dependencies. In 2NF, a relation has no partial dependence, which means it has no non-prime attribute that is dependent on any suitable subset of any table candidate key. Often, the problem may be solved by setting a single column Primary Key.

Third Normal Form:
If a relation meets the requirements for the second normal form and there is no transitive dependency, it is said to be in the third normal form.

Q63. What is OLTP?

OLTP, or online transactional processing, allows huge groups of people to execute massive amounts of database transactions in real time, usually via the internet. A database transaction occurs when data in a database is changed, inserted, deleted, or queried.

What are the differences between OLTP and OLAP?

OLTP stands for online transaction processing, whereas OLAP stands for online analytical processing. OLTP is an online database modification system, whereas OLAP is an online database query response system.

Q64. How to create empty tables with the same structure as another table?

To create empty tables:

Using the INTO operator to fetch the records of one table into a new table while setting a WHERE clause to false for all entries, it is possible to create empty tables with the same structure. As a result, SQL creates a new table with a duplicate structure to accept the fetched entries, but nothing is stored into the new table since the WHERE clause is active.

Q65. What is PostgreSQL?

In 1986, a team lead by Computer Science Professor Michael Stonebraker created PostgreSQL under the name Postgres. It was created to aid developers in the development of enterprise-level applications by ensuring data integrity and fault tolerance in systems. PostgreSQL is an enterprise-level, versatile, resilient, open-source, object-relational database management system that supports variable workloads and concurrent users. The international developer community has constantly backed it. PostgreSQL has achieved significant appeal among developers because to its fault-tolerant characteristics.
It’s a very reliable database management system, with more than two decades of community work to thank for its high levels of resiliency, integrity, and accuracy. Many online, mobile, geospatial, and analytics applications utilise PostgreSQL as their primary data storage or data warehouse.

Q66. What are SQL comments?

SQL Comments are used to clarify portions of SQL statements and to prevent SQL statements from being executed. Comments are quite important in many programming languages. The comments are not supported by a Microsoft Access database. As a result, the Microsoft Access database is used in the examples in Mozilla Firefox and Microsoft Edge.
Single Line Comments: It starts with two consecutive hyphens (–).
Multi-line Comments: It starts with /* and ends with */.

Let’s move to the next question in this SQL Interview Questions.

Q67. What is the difference between the RANK() and DENSE_RANK() functions?

The RANK() function in the result set defines the rank of each row within your ordered partition. If both rows have the same rank, the next number in the ranking will be the previous rank plus a number of duplicates. If we have three records at rank 4, for example, the next level indicated is 7.

The DENSE_RANK() function assigns a distinct rank to each row within a partition based on the provided column value, with no gaps. It always indicates a ranking in order of precedence. This function will assign the same rank to the two rows if they have the same rank, with the next rank being the next consecutive number. If we have three records at rank 4, for example, the next level indicated is 5.

Q68. What is SQL Injection?

SQL injection is a sort of flaw in website and web app code that allows attackers to take control of back-end processes and access, retrieve, and delete sensitive data stored in databases. In this approach, malicious SQL statements are entered into a database entry field, and the database becomes exposed to an attacker once they are executed. By utilising data-driven apps, this strategy is widely utilised to get access to sensitive data and execute administrative tasks on databases. SQLi attack is another name for it.

The following are some examples of SQL injection:

  • Getting access to secret data in order to change a SQL query to acquire the desired results.
  • UNION attacks are designed to steal data from several database tables.
  • Examine the database to get information about the database’s version and structure

Q69. How many Aggregate functions are available in SQL?

SQL aggregate functions provide information about a database’s data. AVG, for example, returns the average of a database column’s values.

SQL provides seven (7) aggregate functions, which are given below:

AVG(): returns the average value from specified columns.
COUNT(): returns the number of table rows, including rows with null values.
MAX(): returns the largest value among the group.
MIN(): returns the smallest value among the group.
SUM(): returns the total summed values(non-null) of the specified column.
FIRST(): returns the first value of an expression.
LAST(): returns the last value of an expression.

Q70. What is the default ordering of data using the ORDER BY clause? How could it be changed?

The ORDER BY clause in MySQL can be used without the ASC or DESC modifiers. The sort order is preset to ASC or ascending order when this attribute is absent from the ORDER BY clause.

Q71. How do we use the DISTINCT statement? What is its use?

The SQL DISTINCT keyword is combined with the SELECT query to remove all duplicate records and return only unique records. There may be times when a table has several duplicate records.
The DISTINCT clause in SQL is used to eliminate duplicates from a SELECT statement’s result set.

Q72. What are the syntax and use of the COALESCE function?

From a succession of expressions, the COALESCE function returns the first non-NULL value. The expressions are evaluated in the order that they are supplied, and the function’s result is the first non-null value. Only if all of the inputs are null does the COALESCE method return NULL.

The syntax of COALESCE function is COALESCE (exp1, exp2, …. expn) 

 

Q73. What is the ACID property in a database?

ACID stands for Atomicity, Consistency, Isolation, Durability. It is used to ensure that the data transactions are processed reliably in a database system. 

  • Atomicity: Atomicity refers to the transactions that are completely done or failed where transaction refers to a single logical operation of a data. It means if one part of any transaction fails, the entire transaction fails and the database state is left unchanged.
  • Consistency: Consistency ensures that the data must meet all the validation rules. In simple words,  you can say that your transaction never leaves the database without completing its state.
  • Isolation: The main goal of isolation is concurrency control.
  • Durability: Durability means that if a transaction has been committed, it will occur whatever may come in between such as power loss, crash or any sort of error.

Q74. What do you mean by “Trigger” in SQL?

Trigger in SQL is are a special type of stored procedures that are defined to execute automatically in place or after data modifications. It allows you to execute a batch of code when an insert, update or any other query is executed against a specific table.

Q75. What are the different operators available in SQL?

There are three operators available in SQL, namely:

  1. Arithmetic Operators
  2. Logical Operators
  3. Comparison Operators

Apart from this SQL Interview Questions blog, if you want to get trained from professionals on this technology, you can opt for structured training from edureka! 

Q76.  Are NULL values same as that of zero or a blank space? 

A NULL value is not at all same as that of zero or a blank space. NULL value represents a value which is unavailable, unknown, assigned or not applicable whereas a zero is a number and blank space is a character.

Q77. What is the difference between cross join and natural join?

The cross join produces the cross product or Cartesian product of two tables whereas the natural join is based on all the columns having the same name and data types in both the tables.

Q78. What is subquery in SQL?

A subquery is a query inside another query where a query is defined to retrieve data or information back from the database. In a subquery, the outer query is called as the main query whereas the inner query is called subquery. Subqueries are always executed first and the result of the subquery is passed on to the main query. It can be nested inside a SELECT, UPDATE or any other query. A subquery can also use any comparison operators such as >,< or =.

Q79. What are the different types of a subquery?

There are two types of subquery namely, Correlated and Non-Correlated.

Correlated subquery: These are queries which select the data from a table referenced in the outer query. It is not considered as an independent query as it refers to another table and refers the column in a table.

Non-Correlated subquery: This query is an independent query where the output of subquery is substituted in the main query.

Let’s move to the next question in this SQL Interview Questions.

Q80. List the ways to get the count of records in a table?

To count the number of records in a table in SQL, you can use the below commands:

SELECT * FROM table1

SELECT COUNT(*) FROM table1

SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid < 2

Apart from this SQL Interview Questions Blog, if you want to get trained from professionals on this technology, you can opt for structured training from edureka! 

Q81. Write a SQL query to find the names of employees that begin with ‘A’?

To display name of the employees that begin with ‘A’, type in the below command:

1
SELECT * FROM Table_name WHERE EmpName like 'A%'

Q82. Write a SQL query to get the third-highest salary of an employee from employee_table?

1
2
3
4
5
6
SELECT TOP 1 salary
FROM(
SELECT TOP 3 salary
FROM employee_table
ORDER BY salary DESC) AS emp
ORDER BY salary ASC;

Q83. What is the need for group functions in SQL? 

Group functions work on the set of rows and return one result per group. Some of the commonly used group functions are: AVG, COUNT, MAX, MIN, SUM, VARIANCE.

Q84. What is a Relationship and what are they?

Relation or links are between entities that have something to do with each other. Relationships are defined as the connection between the tables in a database. There are various relationships, namely:

  • One to One Relationship.
  • One to Many Relationship.
  • Many to One Relationship.
  • Self-Referencing Relationship.

Q85.  How can you insert NULL values in a column while inserting the data?

NULL values in SQL can be inserted in the following ways:

  • Implicitly by omitting column from column list.
  • Explicitly by specifying NULL keyword in the VALUES clause

Q86. What is the main difference between ‘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);

Q87. Why are SQL functions used?

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

Q88. 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.

Q89. What do you mean by recursive stored procedure?

Recursive stored procedure refers to a stored procedure which calls by itself until it reaches some boundary condition. This recursive function or procedure helps the programmers to use the same set of code n number of times.

Q90. What is CLAUSE in SQL?

SQL clause helps to limit the result set by providing a condition to the query. A clause helps to filter the rows from the entire set of records.

For example – WHERE, HAVING clause.

Apart from this SQL Interview Questions Blog, if you want to get trained from professionals on this technology, you can opt for a structured training from edureka! Click below to know more.

Q91. What is the difference between ‘HAVING’ CLAUSE and a ‘WHERE’ CLAUSE?

HAVING clause can be used only with SELECT statement. It is usually used in a GROUP BY clause and whenever GROUP BY is not used, HAVING behaves like a WHERE clause.
Having Clause is only used with the GROUP BY function in a query whereas WHERE Clause is applied to each row before they are a part of the GROUP BY function in a query.

Q92. List the ways in which  Dynamic SQL can be executed?

Following are the ways in which dynamic SQL can be executed:

  • Write a query with parameters.
  • Using EXEC.
  • Using sp_executesql.

Q93. What are the various levels of constraints?

Constraints are the representation of a column to enforce data entity and consistency. There are two levels  of a constraint, namely:

  • column level constraint
  • table level constraint

Q94. How can you fetch common records from two tables?

You can fetch common records from two tables using INTERSECT. For example:


Select studentID from student. <strong>INTERSECT </strong> Select StudentID from Exam

Q95. List some case manipulation functions in SQL?

There are three case manipulation functions in SQL, namely:

  • 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’)

Apart from this SQL Interview Questions blog, if you want to get trained from professionals on this technology, you can opt for a structured training from edureka! Click below to know more.

 Q96. What are the different set operators available in SQL?

Some of the available set operators are – Union, Intersect or Minus operators.

Q97. What is an ALIAS command?

ALIAS command in SQL is the name that can be given to any table or a column. This alias name can be referred in WHERE clause to identify a particular table or a column.

For example-

Select emp.empID, dept.Result from employee emp, department as dept where emp.empID=dept.empID

In the above example, emp refers to alias name for employee table and dept refers to alias name for department table.

Let’s move to the next question in this SQL Interview Questions.

Q98. What are aggregate and scalar functions?

Aggregate functions are used to evaluate mathematical calculation and returns a single value. These calculations are done from the columns in a table. For example- max(),count() are calculated with respect to numeric.

Scalar functions return a single value based on the input value. For example – UCASE(), NOW() are calculated with respect to string.

Let’s move to the next question in this SQL Interview Questions.

Q99. How can you fetch alternate records from a table?

You can fetch alternate records i.e both odd and even row numbers. For example- To display even numbers, use the following command:

Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=0

Now, to display odd numbers:

Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=1

Q100. Name the operator which is used in the query for pattern matching?

LIKE operator is used for pattern matching, and it can be used as -.

  1. % – It matches zero or more characters.

For example- select * from students where studentname like ‘a%’

_ (Underscore) – it matches exactly one character.
For example- select * from student where studentname like ‘abc_’

Apart from this SQL Interview Questions Blog, if you want to get trained from professionals on this technology, you can opt for structured training from edureka! 

Q101. How can you select unique records from a table?

You can select unique records from a table by using the DISTINCT keyword.

Select DISTINCT studentID from Student

Using this command, it will print unique student id from the table Student.

Q102. How can you fetch first 5 characters of the string?

There are a lot of ways to fetch characters from a string. For example:

Select SUBSTRING(StudentName,1,5) as studentname from student

Q103What is the main difference between SQL and PL/SQL?

SQL is a query language that allows you to issue a single query or execute a single insert/update/delete whereas PL/SQL is Oracle’s “Procedural Language” SQL, which allows you to write a full program (loops, variables, etc.) to accomplish multiple operations such as selects/inserts/updates/deletes. 

Q104. What is a View?

A view is a virtual table which consists of a subset of data contained in a table. Since views are not present, it takes less space to store. View can have data of one or more tables combined and it depends on the relationship.

Let’s move to the next question in this SQL Interview Questions.

Q105. What are Views used for?

A view refers to a logical snapshot based on a table or another view. It is used for the following reasons:

  • Restricting access to data.
  • Making complex queries simple.
  • Ensuring data independence.
  • Providing different views of same data.

Q106. What is a Stored Procedure?

A Stored Procedure is a function which consists of many SQL statements to access the database system. Several SQL statements are consolidated into a stored procedure and execute them whenever and wherever required which saves time and avoid writing code again and again.

Q107. List some advantages and disadvantages of Stored Procedure?

Advantages:

A Stored Procedure can be used as a modular programming which means create once, store and call for several times whenever it is required. This supports faster execution. It also reduces network traffic and provides better security to the data.

Disadvantage:

The only disadvantage of Stored Procedure is that it can be executed only in the database and utilizes more memory in the database server.

Q108. List all the types of user-defined functions?

There are three types of user-defined functions, namely:

  • Scalar Functions
  • Inline Table-valued functions
  • Multi-statement valued functions

Scalar returns the unit, variant defined the return clause. Other two types of defined functions return table.

Let’s move to the next question in this SQL Interview Questions.

Q109. What do you mean by Collation?

Collation is defined as a set of rules that determine how data can be sorted as well as compared. Character data is sorted using the rules that define the correct character sequence along with options for specifying case-sensitivity, character width etc.

Let’s move to the next question in this SQL Interview Questions.

Q110. What are the different types of Collation Sensitivity?

Following are the different types of collation sensitivity:

  • Case Sensitivity: A and a and B and b.
  • Kana Sensitivity: Japanese Kana characters.
  • Width Sensitivity: Single byte character and double-byte character.
  • Accent Sensitivity.

Apart from this SQL Interview Questions Blog, if you want to get trained from professionals on this technology, you can opt for structured training from edureka! 

Q111. What are Local and Global variables?

Local variables:

These variables can be used or exist only inside the function. These variables are not used or referred by any other function.

Global variables:

These variables are the variables which can be accessed throughout the program. Global variables cannot be created whenever that function is called.

Q112. What is Auto Increment in SQL?

Autoincrement keyword allows the user to create a unique number to get generated whenever a new record is inserted into the table.
This keyword is usually required whenever PRIMARY KEY in SQL is used.

AUTO INCREMENT keyword can be used in Oracle and IDENTITY keyword can be used in SQL SERVER.

Q113. What is a Datawarehouse?

Datawarehouse refers to a central repository of data where the data is assembled from multiple sources of information. Those data are consolidated, transformed and made available for the mining as well as online processing. Warehouse data also have a subset of data called Data Marts.

Q114. What are the different authentication modes in SQL Server? How can it be changed?

Windows mode and Mixed Mode – SQL and Windows. You can go to the below steps to change authentication mode in SQL Server:

  • Click Start> Programs> Microsoft SQL Server and click SQL Enterprise Manager to run SQL Enterprise Manager from the Microsoft SQL Server program group.
  • Then select the server from the Tools menu.
  • Select SQL Server Configuration Properties, and choose the Security page.

Q115. What are STUFF and REPLACE function?

STUFF Function: This function is used to overwrite existing character or inserts a string into another string. Syntax:
STUFF(string_expression,start, length, replacement_characters)
where,
string_expression: it is the string that will have characters substituted
start: This refers to the starting position
length: It refers to the number of characters in the string which are substituted.
replacement_string: They are the new characters which are injected in the string.

 

REPLACE function: This function is used to replace the existing characters of all the occurrences. Syntax:
REPLACE (string_expression, search_string, replacement_string)


Comments