Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Saturday, June 20, 2020

Java Interview @ Fresher Level - 3

Hi friends,

In this post, I'm sharing interview questions asked @ fresher level.

You can also go through my other fresher level interview posts:



Question 1:

Name the types of  SQL databases.

Answer:

There are multiple SQL databases. Few are listed below:

  • MySQL
  • SQL Server
  • Oracle 
  • Postgres


Question 2:

What is the difference between MySQL and SQL Server?

Answer:

There are multiple differences between MySQL and SQL server databases:

  • MySQL is an open source RDBMS [owned by Oracle] , whereas SQL Server is a microsoft product.
  • MySQL supports more programming languages than supported by SQL server. e.g.: MySQL supports Perl, Scheme, Tcl, Eiffel etc.  which are not supported by SQL server.
  • Multiple storage engine[InnoDB, MyISAM] support makes MySQL  more flexible than SQL Server.
  • While using MySQL, RDBMS blocks the database while backing up the data. And the data restoration process is time-consuming due to execution of multiple SQL statements. Unlike MySQL, SQL server does not block the database while backing up the data.
  • SQL server is more secure than MySQL. MySQL allows database file to be accessed and manipulated by other processes at runtime. But SQL server  does not allow any process to access or manipulate it's database files or binaries.
  • MySQL doesn't allow to cancel a query mid-execution. On the other hand, SQL server allows us to cancel a query execution mid-way in the process.     



Question 3:

Why should we never compare Integer using == operator?

Answer:

Java 5 provides autoboxing/unboxing.
So, we store int to wrapper class Integer. But we should not use == operator to compare Integer objects. e.g.:

Integer i = 127;
Integer j = 127;

i == j will give true.

Integer ii =  128;
Integer jj = 128;

ii == jj  will give false.

It is so because, Integer.valueOf() method caches int values ranging from -127 to 127. So, between this range, it will return same object.
After that, it will create new object.

Note:
Integer i = 127;
Integer j = new Integer(128);

Now, == operator will give false. As , new operator will create a new object.

 

Question 4:

Why to use lock classes from concurrent API when we have synchronization?

Answer:

Lock classes in concurrent API provide fine-grained control over locking.

Interfaces: Lock, ReadWriteLock
Classes: ReentrantLock, ReentrantReadWriteLock



Question 5:

What are the methods for fine-grained control?

Answer:

ReentrantLock provides multiple methods for more fine-grained control:

  • isLocked()
  • tryLock()
  • tryLock(long milliseconds, TimeUnit tu)
The tryLock() method tries to acquire the lock without pausing the thread. That is, if the thread couldn't acquire the lock because it was held by another thread, then it returns immediately instead of waiting for the lock to be released.

We can also specify a timeout in the tryLock() method to wait for the lock to be available:

lock.tryLock(1, TimeUnit.SECONDS);

The thread will now pause for one second and wait for the lock to be available. If the lock couldn't be acquired within 1 second , then the thread returns.



Question 6:

What is ReentrantReadWriteLock?

Answer:

ReadWriteLock consists of a pair of locks - one for read and one for write access. The read lock may be held by multiple threads simultaneously as long as the write lock is not held by any thread.

ReadWriteLock allows for an increased level of concurrency. It performs better compared to other locks in applications where there are fewer writes than reads. 


Question 7:

What is the difference between Lock and synchronized keyword?

Answer:

Following are the differences between Lock and synchronized keyword:

  • Having a timeout trying to get access to a synchronized block is not possible. Using lock.tryLock(long timeout, TimeUnit tu), it is possible.
  • The synchronized block must be fully contained within a single method. A lock can have it's calls to lock() and unlock() in separate methods.


Question 8:

Why to use Executor framework?

Answer:

We can use executor framework to decouple command submission from command execution.

Executor framework gives us the ability to create and manage threads. 

There are 3 interfaces defined in executor framework:

  • Executor
  • ExecutorService
  • ScheduledExecutorService




Question 9:

How many groups of collection interfaces are there?

Answer:

There are two groups of collection interfaces:

  • Collection
    • List
      • ArrayList
      • Vector
      • LinkedList
    • Queue
      • LinkedList
      • PriorityQueue
    • Set
      • HashSet
      • LinkedHashSet
      • SortedSet
        • TreeSet
  • Map
    • HashMap
    • HashTable
    • SortedMap
      • TreeMap



Question 10:

What is the definition of Iterable interface?

Answer:

public interface Iterable<T>{

    public Iterator<T> iterator();
}


That's all for this post.
Thanks for reading!!



Tuesday, March 10, 2020

Incedo Interview on SQL knowledge

Hi Friends, 

In this post I'm sharing SQL round interview questions-answers asked in Incedo.

You can also refer my other interview posts here:







Question 1:

What are the JDBC statement interfaces?

Answer:

JDBC statement interfaces are used for accessing the database.

These are of 3 types:


  1. Statement
  2. PreparedStatement
  3. CallableStatement


Statement: Use this for general purpose access to the database. It is useful when we are using static SQL statements at runtime. The Statement interface cannot accept parameters.

PreparedStatement: It is used when we plan to use SQL statements many times. This interface accepts input parameters at runtime.

CallableStatement: It is used when we want to access database stored procedures. This interface also accepts runtime input parameters. 



Creating Statement Object:

We need to create Statement object before we can use it. We can call createStatement() method on Connection object as follows:

try{
    Statement st = Connection.createStatement();
}
catch(Exception e){

}

Now, we can call any of the methods given below to execute SQL statement:


  • execute()
  • executeUpdate()
  • executeQuery() 



Creating PreparedStatement Object:

try{
    String SQL = "update Student set age = ? where id = ?";
    Statement st = Connection.prepareStatement(SQL);
}
catch(Exception e){

}

All parameters in JDBC are represented by the ? symbol, which is known as the parameter marker. We must supply values for each parameter before executing the SQL statement.




Question 2:

What is the difference between BLOB and CLOB?

Answer:

Blob and Clob are both known as LOB [Large Object Types].

BLOB: It is a variable length Binary large object string that can be upto 2GB long. Primarily intended to hold non-traditional data such as voice or mixed media.

CLOB: It is a variable length character large object string that can be upto 2GB long.  A CLOB can be used to store single byte character strings or multibyte character-based data.

Following are the differences between BLOB and CLOB:

  1. The full form of Blob is Binary Large Object. The full form of Clob is Character Large Object.
  2. Blob is used to store large binary data. Clob is used to store large textual data.
  3. Blob stores values in the form of binary streams. Clob stores values in the form of character streams.
  4. Using Clob, we can store files like text files, PDF documents, word documents etc. Using Blob, we can store files like videos, images, gifs and audio files.
  5. MySQL supports Blob with the following datatypes: 
    1. TinyBlob
    2. Blob
    3. MediumBlob
    4. LongBlob
          MySQL supports Clob with the following datatypes:
    1. TinyText
    2. Text
    3. MediumText
    4. LongText         
       6. In JDBC API, it is represented by java.sql.BLOB interface.  While Clob is represented by java.sql.Clob interface.





Question 3:


What is the benefit of using PreparedStatement?

Answer:

PreparedStatements help us prevent SQL injections attack.

In this the query and the data are sent to the database server separately.

While using prepared statement, we first send prepared statement to the DB server and then we send the data by using execute() method.

e.g.:

$db-> prepare("Select * from Users where id = ?");

This exact query is sent to the server. Then we send the data in second request like:

$db->execute($data);


If we don't use prepared statement then, SQL injection attack can occur like:

$spoiledData = "1; DROP table Users";
$query = "Select * from Users where id=$spoiledData";

will produce a malicious sequence:

Select * from Users where id = 1; DROP table Users;



Question 4:

How to handle indexes in JDBC?

Answer:

Indexes in a table are pointers to the data which speeds up the retrieval of data from table.
If we use indexes, INSERT and UPDATE statements execute slower whereas SELECT and WHERE get executed faster.

Creating an Index:

create index index_name on table_name(column_name);

Displaying the Index:

Show indexes from table_name;

Dropping the index:

drop index index_name;


That's all for this post.
Hope this post helps everybody in their SQL interviews.


Thursday, March 5, 2020

SQL based interview-1

Hi Friends,

In this post, I'm sharing SQL interview questions/Queries that are asked in Java interviews.

These are some SQL queries and questions that are frequently asked in Java interviews:


Question 1:

What is the difference between MySQL and SQL Server?

Answer:

Difference between MySQL and SQL server are as follows:


  • MySQL server is owned by Oracle while SQL server is owned and managed by Microsoft
  • MySQL supports multiple languages like Perl, Scheme, Tcl, Eiffel etc than SQL server.
  • MySQL supports multiple storage engines [InnoDB, MYISAM] which makes MySQL server more flexible than SQL server.
  • MySQL blocks the database while backing up the data.  And the data restoration is time consuming due to execution of multiple SQL statements. Unlike MySQL, SQL server doesn't block database while backing up the data.
  • SQL Server is more secure than MySQL. MySQL allows database files to be accessed and manipulated by other processes at runtime. But SQL server doesn't allow any process to access or manipulate it's database files or binaries.
  • MySQL doesn't allow to cancel a query mid-execution. On the other hand, SQL server allows us to cancel a query execution mid-way in the process.




Question 2:

What is a Primary key ? How is it different from Unique key?

Answer:

Primary key is a column or set of columns that uniquely identifies each row in the table. There will be only 1 primary key per table.

Important points about Primary key:


  • Null values are not allowed.
  • It must contain unique values. Duplicates are not allowed.
  • If the primary key contains multiple columns , the combination of values of these columns must be unique.
  • When we define a primary key for a table, MySQL automatically creates an index named primary.

Difference between Primary key and Unique key:

  • Primary can be only 1 per table. Unique can be many per table.
  • Primary key doesn't allow null value. While Unique key allows null value.
  • Primary key can be made foreign key in another table. While Unique can not be made foreign key in MySQL but it can be made foreign key in SQL server.
  • By default primary key is clustered index and data in the database table is physically organized in the sequence of clustered index. By default, unique key is a unique non-clustered index.




Question 3:

What is a join and why to use it?

Answer:

A join clause is used to access/retrieve data from multiple tables based on the relationship between the fields of the tables.
Keys play a major role when Joins are used.



Question  4:

What are different normalization forms? Explain.

Answer:

There are multiple normalization forms available in SQL:


  • 1NF
  • 2NF
  • 3NF
  • BCNF: Boyce Codd Normal Form
  • 4NF

Explanation of each normalized form:

1NF Rules:

  • Each table cell should contain a single value.
  • Each record needs to be unique 

2NF Rules:

  • Be in 1NF
  • Single column primary key

3NF Rules:

  • Be in 2NF
  • Has no transitive functional dependencies



Question 5:

What is an index and types of indexes?

Answer:


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

There are following types of indexes:


  • Normal Index
  • Unique Index
  • Clustered Index
  • Non-Clustered Index
  • BitMap Index
  • Composite Index
  • B-Tree Index
  • Function based index

Unique Index:
    This index doesn't allow the field to have duplicate value if the column is unique indexed.  If a  primary key is defined , 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:
    This index doesn't alter the physical order of the table and maintains a logical order of the data. 
    Each table can have many non-clustered indexes.



Question 6:

What is a subquery and what are types of subqueries?

Answer:


A query within a query is called a subquery. The outer is called an main query  and inner query os called a subquery. Subquery is always executed first and the result of subquery is passed to the main query.

There are two types of subqueries:

Correlated Query: It can't be considered as independent query but it can refer the column in a table listed in the FROM of the main query.


NonCorrelated Query:   It can be considered as an independent query and the output of subquery are substituted in the main query.




Question 7:

What is the difference between char and varchar2?

Answer:

Both char and varchar2 are used to display character datatype but varchar2 is used for character strings of variable length whereas char is used for strings of fixed length.

e.g.: char(10) can store only 10 characters  and will not be able to store a string of any other length whereas varchar(10) can store any length till 10 characters.


Question 8:

What is the use of UNION clause?

Answer:

UNION clause is used to remove duplicate records from the result of a query.


Question 9:

Which aggregate functions are there in SQL?

Answer:

There are multiple aggregate functions in SQL:


  • MIN()
  • MAX()
  • SUM()
  • COUNT()
  • FIRST()
  • LAST()
  • AVG()



Question 10:

What is a View in SQL and how to create and execute a View ?

Answer:

A View can be defined as a virtual table that consists of rows and columns from one or more tables.

Data in the virtual table is not stored permanently.

Note: Views are stored in system tables : sys.sysobjvalues

Use case or benefits of View:


  • Views can hide complexity: If we have a query that requires joining several tables  or have complex logic or calculations , we can code all that logic into a view, then select from the View just like you would a table.
  • Views can be used as a security mechanism:  View can select certain columns and/or rows from a table (or tables) and permissions set on the view instead of the underlying tables. This allows surfacing only the data that a user needs to see.


Creating View:

Create View view_name AS
SELECT column1 , column2, ...
FROM table_name
WHERE condition;


Create View [Items Above Average Price] AS
SELECT ItemName, Price
From Orders
where Price > (Select AVG(Price) from Orders);

Note: "Items Above Average Price" is the view name.


Querying the above created View:

Select * from [Items Above Average Price]



That's all from this post.

Thanks for reading.



CAP Theorem and external configuration in microservices

 Hi friends, In this post, I will explain about CAP Theorem and setting external configurations in microservices. Question 1: What is CAP Th...