SQL Interview Questions

1. What are differences between the DELETE and TRUNCATE statement?

Answer

Delete only deletes a row and is slower than truncate. Truncate deletes all the rows and cannot be rolled back.

2. What are the different subsets of SQL?

Answer

Data Definition Language (Allows you to create and delete objects), Data Manipulation Language (Allows manipulation of objects) and Data Control Language (Allows you to control permissions).

3. What do you mean by DBMS? The different types?

Answer

Database Management System allows a user to interact with a database. The two types are Relational Database Management System (Data is stored in tables MYSQL) and Non-Relational Database Management System (No concept Mongo).

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

Answer

A table is a collection of columns and rows. Where field is just the columns.

5. What are the joins in SQL?

Answer

Inner, Right, Left and Full Join. They are used to combine rows from different tables based on columns.

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

Answer

VARCHAR2 is variable length in memory where CHAR is fixed at the value you set it.

7. What is a Primary Key?

Answer

A column that is used to uniquely identify a row. Never NULL and Always unique.

8. What are Constraints?

Answer

They are used to make limits on data types. Some are NOT NULL, UNIQUE and DEFAULT.

9. What is the difference between SQL and MYSQL?

Answer

SQL is the language Structured Query Language where MySQL is a database.

10. What is a Unique Key?

Answer

It is used to uniquely identify a row. No NULL values are allowed and two values cannot be the same.

11. What is a Foreign Key?

Answer

It references a primary key in another table.

12. What do you mean by data integrity?

Answer

The accuracy and consistency of data stored in a database.

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

Answer

Clustered is used to sort out rows based on the column that is clustered. It’s faster to retrieve then unclustered columns. There can only be one cluster per table.

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

Answer

You use GetDate()

15. What are the different types of joins?

Answer

Inner, Right, Left, and Full Join

16. What do you mean by Denormalization?

Answer

A technique used to optimize a database so that reading from it is faster but writing to it can be slower.

17. What are Entities and Relationships?

Answer

The data a table stores represents entities and the relationships is the links between the entities.

18. What is an Index?

Answer

It allows for fast retrieval of data by creating an entry for each value.

19. Explain the different types of Index.

Answer

Unique – does not allow a field to have more than one of the same value. Clustered is where the index is reordered based on key value. Non-Clustered maintains the order of the logical data.

20. What is Normalization and what are the advantages?

Answer

Normalization is the process of organizing data. Some advantages are speed, efficiency and security.

21. What is the difference between the drop and Truncate commands?

Answer

Drop removes a hole table and cannot be rolled back where truncate just removes all the rows.

22. Explain different types of Normalization.

Answer

1NF, no repeating groups in a row. 2NF, every column in a row depends on a key that depends on the primary key. 3NF every column in a row depends on the primary key.

23. What is ACID property in a database?

Answer

Atomicity, Consistency, Isolation and Durability. Used to make sure data is processed reliably.

24. What do you mean by trigger in SQL?

Answer

Special type of stored procedures that run when an event occurs. Some DML triggers are INSERT, UPDATE or DELETE.

25. What are the different operators available in SQL?

Answer

There are three: Arithmetic, Logical and Comparison.

26. Are null values the same as zero or blank space?

Answer

Zero and Blank Space are characters where NULL means no value can be found.

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

Answer

Natural Join requires that both tables have the same columns. Cross join will create a new column.

28. What is subquery in SQL?

Answer

It’s a query inside another query.

29. What are the different types of a subquery?

Answer

Correlated relies on the values of the other queries it’s nested in to work where Non-Correlated does not need the other values to work.

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

Answer

SELECT * FROM table1;

SELECT COUNT(*) FROM table1;

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

Answer

SELECT * FROM aTable WHERE name LIKE 'A%';

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

Answer

SELECT TOP 3 salary FROM employee_table;

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

Answer

They are mathematical functions to operate on a set of rows to give one result per set.

34. What is a Relationship and what are they?

Answer

Links between entities that have something to do with each other. One to One, One to Many, Many to One and Self-Referencing.

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

Answer

Either omit the column or write NULL.

36. What is the main difference between ‘BETWEEN’ and ‘IN’ condition operators?

Answer

BETWEEN is used to check in a range of rows where IN is the specific rows.

37. Why are SQL functions used?

Answer

To perform calculations and modify data.

38. What is the need of MERGE statement?

Answer

It makes changes in one table based on the values of another table.

39. What do you mean by recursive stored procedure?

Answer

It’s stored procedure that calls itself until it reaches a condition.

40. What is the CLAUSE in SQL?

Answer

It limits the results by providing a condition to query.

41. What is the difference bewteen ‘HAVING’ CLAUSE and a ‘WHERE’ CLAUSE?

Answer

The WHERE clause is only used to filter rows where the HAVING clause allows you to filter groups.

42. List ways in which Dynamic SQL can be executed?

Answer

A query with parameters, using EXEC and using sp_executesql.

43. What are the various levels of constraints?

Answer

Column and table level constraints.

44. How can you fetch common records from the two tables?

Answer

Using INTERSECT.

45. List some manipulation functions in SQL.

Answer

LOWER, UPPER, INITCAP.

46. What are the different operators available in SQL?

Answer

Union, Intersect and Minus.

47. What is an ALIAS command?

Answer

A name given to a table or column.

48. What are aggregate and scalar functions?

Answer

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

Answer

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

Answer

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

Answer

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

Answer

53. What is the main difference between SQL and PL/SQL?

Answer

54. What is a View?

Answer

It’s a virtual table based on the results of an SQL statement.

55. What are Views used for?

Answer

56. What is a stored Procedure?

Answer

57. List some advantages and disadvantages of Stored Procedures?

Answer

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

Answer

59. What do you mean by Collation?

Answer

60. What are the different types of Collation Sensitivity?

Answer

61. What are Local and Global variables?

Answer

62. What is Auto Increment in SQL?

Answer

63. What is a Datawarehouse?

Answer

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

Answer

65. What are STUFF and REPLACE function?

Answer

Links I used to answer these questions:

https://www.w3schools.com

https://www.wikipedia.org/

SQL UPDATE Command

In this tutorial we will be using MYSQL Workbench. I will assume you already have MYSQL Workbench set up and are connected to it.

The update command is used to modify existing records in a table.

You can update two different ways. Either using a WHERE clause or without WHERE clause. Using the WHERE clause will allow you to select particular rows. If you don’t use it, all the rows will be changed.

To Start You Need To Select The Database

use sakila;

The above code will select the database called sakila.

If you want to see all the values of your rows use the SELECT clause.

SELECT * from film;

That selects all ( * ) the rows contained in the table film. This will allow you to preview your changes to make sure you’ve done everything accurately. This is an example of the output below.

Now we will change the lanugage_id of row 1 from 1 to 2. To do this we need to use the update command

UPDATE film SET language_id = 2 WHERE film_id = 1;

The above code will go to the film table and look where a film_id is equal to 1 and set that rows language_id to 2.

You can also do something else like the following

UPDATE film SET language_id = 2 WHERE rental_rate = 0.99;

That will change all the rows that have a rental_rate of 0.99. It will change their language_id to 2.

The code below will change all the row’s language_id to 1.

UPDATE film set language_id = 1;

As you can see now the language_id are all back to 1 like how we started.

That was a quick tutorial on using the UPDATE command in SQL.

Interview Questions

What is the JRE?

Answer

The JRE is the Java Runtime Environment. It’s a container for components that allows you to run java files on a machine. It contains the java class libraries and the java virtual machine.

What is the JDK?

Answer

The JDK is the Java Development Kit. The jdk contains jre as well as a compiler to convert the java classes to java byte code.

What is the JVM?

Answer

The JVM is the Java Virtual Machine. It’s a virtual machine that allows a computer to run programs that where compiled in java byte code. The .class files are all written in java byte code.

What is a Singleton Class and whats the best way to implement one?

Answer

It is a class that controls object creation to allow the creation of only one object. The best way to implement a singleton is to use an enum. Java allows only one instance of an enum to be created. I created a quick program to demonstrate implementing an enum. Variables one and two are referenced to the enum. We add the count to only the first variable but its actually only adding to the single enum EnumCount.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Singleton
{
    public static void main(String[] args)
    {
        EnumCount one = EnumCount.INSTANCE;
        EnumCount two = EnumCount.INSTANCE;
 
        one.AddCount();
        one.AddCount();
        one.AddCount();
 
        System.out.println("The count of two is " + two.getCount());
    }
}
 
enum EnumCount {
    INSTANCE;
 
    private int count = 0;
 
    public void AddCount()
    {
        count++;
    }
 
    public int getCount()
    {
        return count;
    }
}

The output will be | The count of two is 3

Can a semaphore act as a mutex?

Answer

Yes it can. You would have to restrict the semaphore to only allow 1 thread to access the resource. A semaphore restricts the number of threads that can access a resource. A mutex only allows one thread to access the resource at a time.

If you were to use a set, how would you determine between a HashSet and a TreeSet?

Answer

A HashSet is implemented using a hashtable where the elements are not ordered. A TreeSet is implemented using a tree structure where the elements are sorted using a tree algorithm.

A HashSet is faster then a TreeSet. If your elements do not require sorting a HashSet is good.

If you have elements that will be null then choose a HashSet. A TreeSet uses compareTo( ) which will throw a NullPointerException if the object is null.

Why should you avoid the finalize() method in the Object class? What are some alternatives?

Answer

The finalize method is not called until the garbage collector is ran. Knowing when that will happen is uncertain. That could result in finalize never being ran.

Two things you could do as an alternative to using finalize:

– Implement a close method and document that it should be called.

– Produce a cleaner class that performs cleanup actions.

Assigning Objects

Is an object a reference?

Assigning objects is pretty important in Java. In Java you have two different types of data types. primitive data types (byte, char, short, int, long, float, double, boolean) and you have reference data types. Objects are reference data types. The content of a reference data type is an address to where the data is stored.

In order to do this first we have to allocate the variable in memory.

// Assigning Objects
Cellphone android;

Above Cellphone is the class we are going to reference and android is the name of the variable that is going to hold the reference to the object.

// Referencing a new object
android = new Cellphone("Samsung");

Here we create a new object of the class called Cellphone. We then send it a parameter Samsung. Then the variable android is given a link to the new object we created.

We can also allocate more then one variable at the same time.

// Two References to a single object
Cellphone samsung1, samsung2;

To reference a new object to samsung1 we do

samsung1 = new Cellphone("Samsung");

Then to assign the reference in samsung1 to samsung2

samsung2 = samsung1;

Abstract Vs Interface

Abstract and Interfaces are two important uses in Java Classes. Here are a few differences between the two of them. At the bottom I put an example of each one being used.

Abstract classes are allowed to have both abstract and non abstract methods. While interface methods are ONLY allowed to have abstract methods.

Abstract

abstract class LaptopsAbstract
{
    public void color(String aColor)
    {
        System.out.println("The laptop color is " + aColor);
    }

    abstract public void type(String aType);
}

Interface

interface LaptopInterface
{
    abstract public void color(String aColor);

    abstract public void type(String aType);
}

Abstract classes DO NOT support multiple inheritance. While Interface classes do allow it.

class Mac implements LaptopInterface, LaptopInterfaceTwo
{

When using Interface classes you have to implement. Using abstract classes you must extend.

Interface

class Mac implements LaptopInterface
{}

Abstract

class Acer extends LaptopsAbstract
{}

Abstract classes can have final, non final, static and non static variables. Interface has only static final variables.

Abstract

abstract class LaptopsAbstract
{
    String color = "black";
    Final int screenSize = 13;
}

Interface

interface LaptopInterface
{
     Static Final int screenSize = 13;
}

An Interface can only extend another interface. An Abstract can extend another class and implement multiple interfaces.

Interface

interface LaptopInterface extends LaptopInterfaceTwo
{}

Abstract

abstract class LaptopsAbstract extends OtherClass implements LaptopInterface
{}

Abstract can have private protected etc. methods. While Interface is only public by default.

Abstract

abstract class LaptopsAbstract
{
    private String color = "black";
}

Interface

interface LaptopInterface
{
    String color = "black";
}

Below is an example of extending Abstract classes

abstract class LaptopsAbstract
{
    private String color = "black";

    public void color(String aColor)
    {
        System.out.println("The laptop color is " + aColor);
    }

    abstract public void type(String aType);

    abstract public void screenSize(int screenSize);
}

class Acer extends LaptopsAbstract
{
    public void type(String aType)
    {
        System.out.println("The tpe of laptop is " + aType);
    }

    public void screenSize(int screenSize)
    {
        System.out.println("The screen size of the laptop is " + screenSize);
    }

    public static void main(String[] args) {
        LaptopsAbstract acer = new Acer();

        acer.type("Acer");
        acer.screenSize(17);
        acer.color("black");
    }
}

Below is an example implementing Interfaces

interface LaptopInterface
{
    String color = "black";

    abstract public void color(String aColor);

    abstract public void type(String aType);

    abstract public void screenSize(int screenSize);
}

class Mac implements LaptopInterface
{
    public void color(String aColor)
    {
        System.out.println("The color is " + aColor);
    }

    public void type(String aType)
    {
        System.out.println("The type is " + aType);
    }

    public void screenSize(int screenSize)
    {
        System.out.println("The screen size is " + screenSize);
    }

    public static void main(String[] args) {
        LaptopInterface aMac = new Mac();

        aMac.color("White");
        aMac.type("Mac");
        aMac.screenSize(13);
    }
}

Encapsulation

Daniel Leygthon's avatarSpace Coding

//com.collabera.encapsulation;
// (Project name here)

class EncapsulationDemo{

    // encapsulation = binding data with methods

    /**
     * The need for encapsulation is to make sure our "private data its safe
     * Since the only way that we will be able to access our data will be through methods
     * public = anyone can access the variable
     *
     */

    // Private variables
    private Integer moneyOwed;
    // We make sure variables are always private
    private String name;


    // Getter, and setter methods that will access our private variables.

    public Integer getMoneyOwed() {
        return moneyOwed;
    }

    public void setTotal(Integer moneyOwed) {
        this.moneyOwed = moneyOwed;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

View original post

Using Class Methods

This is an example of how to use methods in different classes.

Java methods are methods in a class used to perform actions.

They can either be static or public.

Static Methods can be accessed in a class without creating an object.

Below is an example on using a Static Method. I created a class called UsingClassMethods.

public class UsingClassMethods
{  

Then I created a static method called testStaticMethod.

    static void testStaticMethod()
    {

Finally I call the static method testStaticMethod from the main method.

testStaticMethod();

Below is the hole code put together.

public class UsingClassMethods
{  
    //Since this method is static it can be accessed in this class without creating an object of this class
    static void testStaticMethod()
    {
        System.out.println("This is called from a static method in UsingClassMethods\n");
    }

    public static void main(String[] args)
    {
        //This is called from a static method in this class, UsingClassMethods
            testStaticMethod();
    }
}

For Public Methods you need to create an object of the class to access them. Below is an example of an Object called testClassObject that uses the class UsingClassMethods.

        //This creates a new object of this class, UsingClassMethods
        UsingClassMethods testClassObject = new UsingClassMethods();

To access methods in an object you need to first write the object’s name with a dot or .

You can also create an object of a class and access it from another class in a different file. Below you can find my user file. This will be the class used to create an object. It contains a String name and two public methods. The first one setUsername to set the value and the following getUsername to retrieve the value.

//This is the User class as its own file
//It consists of a name string and two methods one to set it and one to retrieve it
public class User
{
    String name = "";

    public void setUsername(String tempName)
    {
        name = tempName;
        System.out.println("The string has been sent to the User class method setUsername\n");
    }


    public void getUsername()
    {
        System.out.println("This is from the User class method getUsername and this is the string sent from UsingClassMethods: " + name +"\n");
    }
}

Finally this is an example of using the User class as an object.

//Class Methods are used to call methods between different classes
public class UsingClassMethods
{
        //This creates an object of the class User called aUser
            User aUser = new User();
            System.out.println("This creates an object of a class called User\n");


        //This is calling the setUsername method from the object called aUser
            aUser.setUsername("Greg");


        //This calling the getUsername method from the object called aUser
            aUser.getUsername();
    }
}

A question to ask yourself. What is the difference between using static and public on methods?

Design a site like this with WordPress.com
Get started