- What is DBMS?
Ans. A Database Management System (DBMS) is system software for creating and managing databases. It serves as an interface between databases and end-users or application programs so that data is consistently organized and remains easily accessible. It allows end-users to create, read, update, and delete data in a database. There are two types of DBMS:
- Relational Database Management System (RDBMS): In RDBMS, the data is stored in relations (tables). Example – MySQL.
- Non-Relational Database Management System (often called NoSQL databases): It stores data in a non-tabular form. Example – MongoDB
- What is SQL?
Ans. SQL (structured querying language) is a computer language used to create, update, and modify a database. It is the standard language for Relational Database System. All the RDMS like MySQL, MS Access, Oracle, and SQL Server use SQL as their standard database language.
- What is MySQL?
And. MySQL is an open-source relational database management system (RDBMS) that is developed and distributed by Oracle Corporation. Supported by various operating systems, such as Windows, Unix, Linux, etc., MySQL can be used to develop different types of applications. Known for its speed, reliability, and flexibility, MySQL is mainly used for developing web applications.
- What are the subsets of SQL? Explain them.
Ans. The following are the three subsets of SQL:
- Data Definition Language (DDL) – It allows end-users to CREATE, ALTER, and DELETE database objects.
- Data Manipulation Language (DML) – With this, you can access and manipulate data. It allows you to Insert, Update, Delete, and Retrieve data from the database.
- Data Control Language (DCL) – This lets you control access to the database. It includes the Grant and Revoke permissions to manipulate or modify the database.
- What is the primary key?
Ans. A primary key constraint uniquely identifies each row/record in a database table. Primary keys must contain unique values. Null value and duplicate values are not allowed to be entered in the primary key column. A table can have only one primary key. It can consist of single or multiple fields.
- What is a foreign key?
Ans. A foreign key (often called the referencing key) is used to link two tables together. It is a column or a combination of columns whose values match a Primary Key in a different table. It acts as a cross-reference between tables because it references the primary key of another table and established a link between them.
- What is RDBMS?
Ans. Relational Database Management System or RDBMS is based on the relational database model and is among the most popular database management systems.
- What are the features of MySQL?
Ans. Here are some of the important features of MySQL:
- It is reliable and easy to use
- It supports standard SQL (Structured Query Language)
- MySQL is secure as it consists of a data security layer that protects sensitive data from unauthorized users
- MySQL has a flexible structure and supports a large number of embedded applications
- It is one of the very fast database languages
- It is a suitable database software for both large and small applications
- MySQL offers very high-performance results compared to other database
- It is supported by many well-known programming languages, such as PHP, Java and C++
- It is free to download and use
- What are the disadvantages of MySQL?
Ans. The disadvantages of MySQL are:
- It is hard to make MySQL scalable
- It does not support a very large database size as efficiently
- MySQL does not support SQL check constraint
- It is prone to data corruption
- What are the differences between MySQL vs SQL?
Ans. This is one of the frequently asked SQL interview questions.
The differences between MySQL and SQL are:
MySQL | SQL |
1. It is a relational database that uses SQL to query a database | 1. It is a query language |
2. MySQL supports multiple storage engines and plug-in storage engines | 2. SQL supports a single storage engine |
3. It is a database that stores the existing data in a database in an organized manner. | 3. SQL is used to access, update, and manipulate the data stored in a database |
4. Supports many platforms | 4. Supports only Linux and Windows |
5. It has a complex syntax | 5. It has a simpler syntax |
- What is a unique key?
Ans. A unique key is a set of one or more than one field/column of a table that uniquely identifies a record in a database table. A primary key is a special kind of unique key.
- Explain the different types of indexes in SQL.
Ans. There are three types of indexes in SQL:
- Unique Index – It does not allow a field to have duplicate values if the column is unique indexed.
- Clustered Index – This index defines the order in which data is physically stored in a table. It reorders the physical order of the table and searches based on key values. There can be only one clustered index per table.
- Non-Clustered Index – It does not sort the physical order of the table and maintains a logical order of the data. Each table can have more than one non-clustered index.
- What is the difference between TRUNCATE and DELETE?
Ans. This is one of the most commonly asked SQL interview questions. The difference between TRUNCATE and DELETE are:
DELETE | TRUNCATE |
Delete command is used to delete a specified row in a table. | Truncate is used to delete all the rows from a table. |
You can rollback data after using the delete statement. | You cannot rollback data. |
It is a DML command. | It is a DDL command. |
It is slower than a truncate statement. | It is faster. |
- What is the difference between:
SELECT * FROM MyTable WHERE MyColumn <> NULL
SELECT * FROM MyTable WHERE MyColumn IS NULL
Ans. The first syntax will not work because NULL means ‘no value’, and you cannot use scalar value operators. This is why there is a separate IS – a NULL predicate in SQL.
- What is the difference between CHAR and VARCHAR?
Ans. CHAR is a fixed-length character data type, while VARCHAR is a variable-length character data type.
- What is a subquery in SQL?What are the different types of a subquery?
Ans. A subquery is a query within another query. When there is a query within a query, the outer query is called the main query, while the inner query is called a subquery. There are two types of a subquery:
- Correlated subquery: It obtains values from its outer query before it executes. When the subquery returns, it passes its results to the outer query.
- Non-Correlated subquery: It executes independently of the outer query. The subquery executes first and then passes its results to the outer query. Both inner and outer queries can run separately.
- What is collation sensitivity?
Ans. Collation sensitivity defines the rules to sort and compare the strings of character data, based on correct character sequence, case-sensitivity, character width, and accent marks, among others.
- What are the different types of collation sensitivity?
Ans. There are four types of collation sensitivity, which include –
- Accent sensitivity
- Case sensitivity
- Kana sensitivity
- Width sensitivity
- What is a “scheduled job” or “scheduled task”?
Ans. Scheduled job or task allows automated task management on regular or predictable cycles. One can schedule administrative tasks and decide the order of the tasks.
- Can you name different types of MySQL commands?
Ans. SQL commands are divided into the following –
- Data Definition Language (DDL)
- Data Manipulation Language (DML)
- Data Control Language (DCL)
- Transaction Control Language (TCL)
- Explain different DDL commands in MySQL.
Ans. DDL commands include –
- CREATE – Used to create the database or its objects like table, index, function, views, triggers, etc.
- DROP – Used to delete objects
- ALTER – Used to change database structures
- TRUNCATE – It erases all records from a table, excluding its database structure
- COMMENT – Used to add comments to the data dictionary
- RENAME – Used to rename a database object
- Explain different DML commands in MySQL.
Ans. This is one of the most popularly asked SQL interview questions.
DML commands include –
- SELECT – Used to select specific database data
- INSERT – Used to insert new records into a table
- UPDATE – It helps in updating existing records
- DELETE – Used to delete existing records from a table
- MERGE – Used to UPSERT operation (insert or update)
- CALL – It is used when you need to call a PL/SQL or Java subprogram
- EXPLAIN PLAN – Used to interpret data access path
- LOCK TABLE – Used to control concurrency
- Explain different DCL commands in MySQL.
Ans. DCL commands are –
- GRANT – It provides user access privileges to the database
- DENY – Used to deny permissions to users
- REVOKE – Used to withdraw user access by using the GRANT command
- Explain different TCL commands in MySQL.
Ans. DCL commands include –
- COMMIT – Used to commit a transaction
- ROLLBACK – Used to roll back a transaction
- SAVEPOINT – Used to roll back the transaction within groups
- SET TRANSACTION – Used to specify transaction characteristics
- What are the different types of Database relationships in MySQL?
Ans. There are three types of Database Relationship –
- One-to-one – Both tables can have only one record
- One-to-many – The single record in the first table can be related to one or more records in the second table
- Many-to-many – Each record in both the tables can be related to any number of records
- What is Normalization?
Ans. Normalization is a database design technique to organize tables to reduce data redundancy and data dependency.
- What are the different types of Normalization?
Ans. There are six different types of Normalization –
- First Normal Form (1NF)
- Second Normal Form (2NF)
- Third Normal Form (3NF)
- Boyce-Codd Normal Form (BCNF)
- Fourth Normal Form (4NF)
- Fifth Normal Form (5NF)
- What is Denormalization?
Ans. Denormalization is a database optimization technique for increasing a database infrastructure performance by adding redundant data to one or more tables.
- Is MySQL query case-sensitive?
Ans. MySQL queries are not case-sensitive by default. The following queries are the same.
SELECT * FROM `table` WHERE `column` = ‘value’
SELECT * FROM `table` WHERE `column` = ‘VALUE’
SELECT * FROM `table` WHERE `column` = ‘VaLuE’
- How many TRIGGERS are allowed in the MySQL table?
Ans. 6 triggers are allowed in the MySQL table:
- BEFORE INSERT
- AFTER INSERT
- BEFORE UPDATE
- AFTER UPDATE
- BEFORE DELETE
- AFTER DELETE
- What are the different column comparison operators in MySQL?
Ans. The =, <>, <=, <, >=, >, <<, >>, < = >, AND, OR or LIKE operator are the comparison operators in MySQL.
Comparisons operators are generally used with SELECT statements. They are used to compare one expression to another value or expression.
- What syntax can we use to get a version of MySQL?
Ans. By using the given query in your phpmyadmin-
SELECT version();
- What is Auto Increment in SQL?
Ans. Auto Increment allows a unique number to be generated whenever a new record is created in a table. Generally, it is the PRIMARY KEY field that we want to be created automatically every time a new record is inserted.
- SQL Server runs in which TCP/IP port? Can it be changed?
Ans. SQL Server runs on port 1433, and it can be changed from the Network Utility TCP/IP properties.
- Name symmetric key encryption algorithms supported in the SQL server.
Ans. SQL Server supports several symmetric key encryption algorithms, such as DES, Triple DES, RC2, RC4, 128-bit RC4, DESX, 128-bit AES, 192-bit AES, and 256-bit AES.
- What is Database Relationship?
Ans. A Database Relationship is defined as the connection between two relational database tables. The primary table has a foreign key that references the primary key of another table. There are three types of Database Relationship –
- One-to-one
- One-to-many
- Many-to-many
- What is faster between a table variable and a temporary table?
Ans. Between these, a table variable is faster mostly as it is stored in memory, whereas a temporary table is stored on disk. In case the size of the table variable exceeds memory size, then both the tables perform similarly.
- Mention the command used to get back the privileges offered by the GRANT command?
Ans. REVOKE command is used to get back the privileges offered by the GRANT command.
- What is a Clause in SQL?
Ans. A clause in SQL is a part of a query that allows users to filter or customize how they want their data to be queried to them. It lets users limit the result set by providing a condition to the query. When there is a large amount of data stored in the database, Clause can be used to query and get data required by the user. Clause function helps filter and analyze data quickly.
For Example – WHERE clause, HAVING clause.
- Explain the ‘WHERE’ Clause and the ‘HAVING’ Clause.
Ans. It is one of the most important SQL interview questions.
The WHERE clause is used to filter the records from the table or used while joining more than one table. It returns the particular value from the table if the specified condition in the WHERE clause is satisfied. It is used with SELECT, INSERT, UPDATE, and DELETE queries to filter data from the table or relation.
For Example:
SELECT * FROM employees
WHERE working_hour > 9;
The HAVING clause is used to filter the records from the groups based on the given condition in the HAVING Clause. It can only be used with the SELECT statement. It returns only those values from the groups in the final result that fulfills certain conditions.
For Example:
SELECT name, SUM(working_hour) AS “Total working hours”
FROM employees GROUP BY name
HAVING SUM(working_hour) > 6;
- What are the differences betweenthe ‘WHERE’ Clause and the ‘HAVING’ Clause?
Ans. Below are the major differences between the ‘WHERE’ Clause and the ‘HAVING’ Clause:
WHERE Clause | HAVING Clause |
It performs filtration on individual rows based on the specified condition. | HAVING clause performs filtration on groups based on the specified condition. |
It can be used without GROUP BY Clause. | It is always used with the GROUP BY Clause. |
WHERE Clause is applied in row operations. | HAVING is applied in column operations. |
We cannot use the WHERE clause with aggregate functions. | This clause works with aggregate functions. |
WHERE comes before GROUP BY | HAVING comes after GROUP BY. |
This clause acts as a pre-filter. | HAVING clause acts as a post-filter. |
WHERE Clause can be used with SELECT, INSERT, UPDATE, and DELETE statement. | This Clause can only be used with SELECT statement. |
Advanced Level SQL Interview Questions
- How to find:
duplicate records with one field?
duplicate records with more than one field?
Ans. Finding duplicate records with one field:
SELECT COUNT(field)
FROM table_name
GROUP BY field
HAVING COUNT(field) > 1
Finding duplicate records with more than one field:
SELECT field1,field2,field3, COUNT(*)
FROM table_name
GROUP BY field1,field2,field3
HAVING COUNT(*) > 1
- What is a constraint, and how many levels of constraints are there?
Ans. Constraints are the representation of a column to enforce data entity and consistency. There are two levels of constraint –
- Column level – Limits only column data
- Table level – Limits whole table data
Following are the most used constraints that can be applied to a table:
- NOT NULL
- UNIQUE
- CHECK
- DEFAULT
- PRIMARY KEY
- FOREIGN KEY
- What are the authentication modes in SQL Server?
Ans. SQL Server has two authentication modes –
- Windows Mode – Default. This SQL Server security model is integrated with Windows
- Mixed Mode – Supports authentication both by Windows and by SQL Server
We can change modes by selecting tools of SQL Server configuration properties and then hover to the security page.
- What is PL/SQL?
Ans. PL/SQL or Procedural Language for SQL was developed by Oracle. It is an extension of SQL and enables the programmer to write code in a procedural format. Both PL/SQL and SQL run within the same server process and have features like – robustness, security, and portability of the Oracle Database.
- What is SQL Profiler?
Ans. SQL Server Profiler is a graphical user interface for creating and saving data about each event of a file. It also allows a system administrator to analyze and replay trace results when a problem is being diagnosed. SQL Server Profiler is used to:
- Examine the problem queries to find the cause of the problem
- Diagnose slow-running queries
- Determine the Transact-SQL statements that lead to a problem
- Monitor the performance of SQL Server
- Correlate performance counters to diagnose problems
- What is the SQL Server Agent?
Ans. SQL Server Agent is a Microsoft Windows service that executes day-to-day tasks or jobs of SQL Server Database Administrator (DBA). This service enables the implementation of tasks on a scheduled date and time.
- What is Data Integrity?
Ans. Data integrity attributes to the accuracy, completeness, and consistency of the data in a database. It also refers to the safety and security of data and is maintained by a collection of processes, rules, and standards that were implemented during the design phase. Three types of data integrity are:
- Column Integrity
- Entity Integrity
- Referential Integrity
- What is the difference between Rename and Alias?
Ans. Rename is actually changing the name of an object. Alias is giving another name (additional name) to an existing object. Rename involves changing the name of a database object and giving it a permanent name whereas Alias is a temporary name given to a database object.
Syntax of a table Alias:
SELECT column1, column2….
FROM table_name AS alias_name
WHERE [condition];
Syntax of a table Rename:
RENAME TABLE {tbl_name} TO {new_tbl_name};
- Which are the main steps in Data Modeling?
Ans. Following are the main steps in Data Modeling:
- Identify and analyze business requirement
- Create a quality conceptual and logical data model
- Select the target database to create scripts for physical schema using a data modeling tool
- What is Referential Integrity?
Ans. Referential integrity is a relational database concept that suggests that accuracy and consistency of data should be maintained between primary and foreign keys.
- What is Business Intelligence?
Ans. Business intelligence (BI) includes technologies and practices for collecting, integrating, analyzing, and presenting business information. It combines business analytics, data mining, data visualization, data tools and infrastructure, and best practices.
- Mention the types of privileges available in SQL?
Ans. Following are the types of privileges used in SQL:
System Privilege: It deals with an object of a specific type and indicates actions on it which include admin that helps users to perform administrative tasks, alter any cache group, and alter any index.
Object Privilege: It helps users to perform actions on an object using commands like table, view, indexes. There are other object privileges used in SQL are EXECUTE, INSERT, SELECT, FLUSH, LOAD, INDEX, UPDATE, DELETE, REFERENCES, etc.
- What is the difference between a clustered and non-clustered index?
Ans. Clustered Index – A clustered index is used to order the rows in a table. It has leaf nodes consisting of data pages. A table can possess only one clustered index.
Non-clustered Index – A non-clustered index stores the data and indices at different places. It also has leaf nodes that contain index rows. A table can possess numerous non-clustered indexes.
- What is ERD?
Ans. ERD or Entity Relationship Diagram is a visual representation of the database structures and shows a relationship between the tables. The ER Diagrams have three basic elements:
- Entities – An entity is a person, place, thing, or event for which data is collected.
- Attributes – It refers to the data we want to collect for an entity. It is a property, trait, or characteristic of an entity, relationship, or another attribute.
- Relationships – It describes how entities interact.
- How will you find the unique values, if a value in the column is repeatable?
Ans. To find the unique values when the value in the column is repeatable, we can use DISTINCT in the query, such as:
SELECT DISTINCT user_firstname FROM users;
We can also ask for several distinct values by using:
SELECT COUNT (DISTINCT user_firstname) FROM users;
- Explain database white box testing.
Ans. White Box Testing is concerned with the internal structure of the database. The users are unaware of the specification details.
- Database white box testing includes testing of database triggers and logical views that support database refactoring.
- Validates database tables, data models, database schema
- Performs module testing of database functions and SQL queries
- Selects default table values to check on database consistency
- Adheres to referential integrity rules
- Exhibit the students who are having the same batch ID and study in the same department as student ids, 1002 and 1004.
Ans.
select x.student_id ,
x.department_id
from students x
where (department_id, batch_id)
in (Select department_id , batch_id
from students
where student_id in (1002,1004))
and x.student_id not in (1002, 1004)
- What is the ACID property in SQL?
Ans. ACID is short for Atomicity, Consistency, Isolation, Durability. It ensures Data Integrity during a transaction.
Atomicity: It means either all the operations (insert, update, delete) inside a transaction take place or none. So, 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. Irrespective of whatever happens in the middle of the transaction, Consistency property will never leave your database in a half-completed state.
Isolation: It means that every transaction is individual. One transaction can’t access the result of other transactions until the transaction is completed.
Durability: It implies that maintaining updates of committed transactions is important. These updates must never be lost. It refers to the ability of the system to recover committed transaction updates if either the system or the storage media fails.
- Explain string functions in SQL?
Ans. SQL string functions are used for string manipulation.
Following are the extensively used SQL string functions:
- UPPER(): Converts character data to upper case
- LOWER(): Converts character data to lower case
- SUBSTRING() : Extracts characters from a text field
- RTRIM(): Removes all whitespace at the end of the string
- LEN(): Returns the length of the value in a text field
- REPLACE(): Updates the content of a string.
- LTRIM(): Removes all whitespace from the beginning of the string
- CONCAT(): Concatenates function combines multiple character strings
- What are the differences between the Primary key and Unique key?
Ans. Differences between Primary key and Unique key are:
Primary Key | Unique Key |
Enforces column uniqueness in a table | Determines a row that isn’t a primary key |
Does not allow NULL values | Accepts one NULL value |
Has only one primary key | Has more than one unique key |
Creates clustered index | Creates non-clustered index |
Primary Key on CREATE TABLE Syntax: CREATE TABLE Students ( ID int NOT NULL PRIMARY KEY, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int); | Unique Key on CREATE TABLE Syntax: CREATE TABLE Students ( ID int NOT NULL UNIQUE, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int); |
- Write the SQL query to convert the string to UPPERCASE and LOWERCASE.
Ans. The SQL query used to convert the string to UPPERCASE and LOWERCASE is:
STRING UPPER(“naukrilearning”); => NAUKRILEARNING
STRING LOWER(“LEARNERS”); => learners
- What is the procedure to hide a specific table name of the schema?
Ans. By using SYNONYMS, we can hide a specific table name of the schema.
Syntax:
CREATE SYNONYM STU for STUDENTS;
After creating the above synonym, we can access the data of STUDENTS table using STU as table name as below
SELECT * from STU;
- What is the syntax to eliminate duplicate rows?
Ans. By using the DISTINCT keyword, we can eliminate duplicate records.
Syntax:
SELECT DISTINCT CLASS_ID
FROM STUDENTS;
- Find out nth highest salary from emp table?
Ans. Syntax:
select salary from
(select salary, rownum EP from
(select salary from employees
order by salary desc))
where EP=n;
- Name the encryption mechanisms in the SQL server.
Ans. This is one of the most popular SQL interview questions. The encryption mechanism used in SQL server are –
- Transact-SQL functions – Individual items can be encrypted as they are inserted or updated using Transact-SQL functions.
- Asymmetric keys – It is made up of a private key and the corresponding public key. Each key can decrypt data encrypted by the other.
- Symmetric keys – It is used for both encryption and decryption.
- Certificates – Also known as a public key certificate, it binds the value of a public key to the identity of the person, device, or service that holds the corresponding private key.
- Transparent Data Encryption – It is a special case of encryption using a symmetric key that encrypts an entire database using that symmetric key.
- What is the procedure to pass variables in a SQL routine?
Ans. Variables can be passed to a SQL routine by using:
- “&” symbol
- SQLPLUS command
- Can a view be updated/inserted/deleted? If yes, at what conditions?
Ans. It is not possible to add the data through a view if the view contains the following:
- Group by clause
- Group functions
- DISTINCT keyword
- Columns defined by expressions
- Pseudo column ROWNUM keyword
- NOT NULL column in the base table that is not selected by the view.
- How can you create an SQL table from another table without copying any values from the old table?
Ans. Syntax:
CREATE TABLE new_table
AS (SELECT *
FROM old_table WHERE 1=2);
This will create a new table with the same structure as the old table with no rows copied.
- Explain what is an inline view?
Ans. An inline view is a SELECT statement in the FROM-clause of another SELECT statement. In-line views are used to reduce complex queries by removing join operations and summarizing multiple separate queries into a single query.
Syntax:
SELECT SALARY FROM
(SELECT SALARY, ROWNUN EP FROM
(SELECT SALARY FROM EMPLOYEES ORDER BY SALARY DESC) )
WHERE EP=7
- What command is used to create a table by copying the structure of another table?
Ans. Syntax:
CREATE TABLE STU AS
SELECT * FROM STUDENTS
WHERE 1=2
Invalid Condition
We have to give the invalid condition in the where clause, where the whole data will copy to the new table (STU table).
- Mention the use of the DROP option in the ALTER TABLE command.
Ans. The use of the DROP option in the ALTER TABLE command is to drop a particular COLUMN.
Syntax:
ALTER TABLE TABLE_NAME
DROP COLUMN COLUMN_NAME
- What are the aggregate functions in SQL?
Ans. SQL aggregate functions allow us to return a single value, which is calculated from values in a column.
Following are the aggregate functions in SQL:
- AVG() : This function returns the average value
- COUNT(): This function returns the number of rows
- MAX() : It returns the largest value
- MIN() : This function returns the smallest value
- ROUND(): This function rounds a numeric field to the number of decimals specified
- SUM() : It returns the sum
- Write the SQL query to update the student names by removing leading and trailing spaces.
Ans. This can be done by using ‘Update’ command with ‘LTRIM’ and ‘RTRIM’ function.
Syntax:
UPDATE StudentDetails
SET FullName = LTRIM(RTRIM(FullName));
- Write the SQL query to fetch alternate records from a table
Ans. Records can be fetched for odd and even row numbers:
- Syntax to fetch even numbers:
Select employeeId from (Select rowno, employeeId from employee) where mod(rowno,2)=0
- Syntax to fetch odd numbers:
Select employeeId from (Select rowno, employeeId from employee) where mod(rowno,2)=1
- How do you return a hundred books starting from the 15th?
Ans. The syntax will be:
SELECT book_title FROM books LIMIT 15, 100.
The first number in LIMIT is the offset, and the second is the number.
- What will the query select all teams that lost either 1, 3, 5, or 7 games?
Ans. We will use-
SELECT team_name FROM teams WHERE team_lost IN (1, 3, 5, 7)
- How will you delete a column?
Ans. We can delete a column by –
ALTER TABLE techpreparation_answers DROP answer_user_id.
- What is the meaning of this query – Select User_name, User_isp From Users Left Join Isps Using (user_id)?
Ans. It means:
SELECT user_name, user_isp FROM users LEFT JOIN isps WHERE users.user_id=isps.user_id
- How will you see all indexes defined for a table?
Ans. By using:
SHOW INDEX FROM techpreparation_questions;
- How would you change a table to InnoDB?
Ans. By using:
ALTER TABLE techpreparation_questions ENGINE InnoDB;
- Name the default port for the MySQL server.
Ans. The default port for the MySQL server is 3306.
- What is the possible way to add five minutes to a date?
Ans. By using:
ADDDATE(techpreparation_publication_date, INTERVAL 5 MINUTE)
- What is the possible way to convert between Unix timestamps and Mysql timestamps?
Ans. Example:
UNIX_TIMESTAMP converts from MySQL timestamp to Unix timestamp
FROM_UNIXTIME converts from Unix timestamp to MySQL timestamp
- How do you implement Enums and sets internally in MySQL?
Ans. To implement an ENUM column, use the given syntax:
CREATE TABLE table_name ( … col ENUM (‘value1′,’value2′,’value3’), … );
- How can we restart SQL Server in the single user or the minimal configuration modes?
Ans. The command line SQLSERVER.EXE used with ‘–m’ will restart SQL Server in the single-user mode.
The command line SQLSERVER.EXE used with ‘–f’ will restart it in the minimal configuration mode.
- What is the use of the tee command in Mysql?
Ans. Tee is a UNIX command that takes the standard output of a Unix command and writes it to both the terminal and a file. Tee followed by a filename turns on MySQL logging to a specified file. It can be paused by a command note.
- Is it possible to save your connection settings to a conf file?
Ans. Yes, it is possible, and you can name it ~/.my.conf. You can also change the permissions on the file to 600 so that it’s not readable by others.
- How to convert numeric values to character strings?
Ans. We can convert numeric values to character strings by using the CAST(value AS CHAR) function, as shown in the following examples:
SELECT CAST(4123.45700 AS CHAR) FROM DUAL;
4123.45700
- Use mysqldump to create a copy of the database?
Ans. mysqldump -h mysqlhost -u username -p mydatabasename > dbdump.sql
- What are federated tables?
Ans. Federated tables allow access to the tables situated on other databases on other servers in MySQL. It lets you access data from a remote MySQL database without using replication or cluster technology. Querying a local FEDERATED table pulls the data from the remote (federated) tables. Data is not stored on the local tables.
- What are the different groups of data types in MySQL?
Ans. There are three groups of data types in MySQL, as listed below:
String Data Types – BINARY, VARBINARY, TINYBLOB, CHAR, NCHAR, VARCHAR, NVARCHAR, TINYTEXT, BLOB, TEXT, MEDIUMBLOB, LONGBLOB, LONGTEXT, ENUM, SET, MEDIUMTEXT.
Numeric Data Types – MEDIUMINT, INTEGER, BIGINT, FLOAT, BIT, TINYINT, BOOLEAN, SMALLINT, DOUBLE, REAL, DECIMAL.
Date and Time Data Types – TIMESTAMP, TIME, DATE, DATETIME, YEAR.
Q93. What is the procedure to concatenate two character strings?
Ans. To concatenate various character strings into one, you can use the CONCAT() function. Example:
SELECT CONCAT(’Naukri’,’ Learning’) FROM DUAL;
Naukri Learning
SELECT CONCAT(‘Learner’,’Thing’) FROM DUAL;
Learner Thing
- What is the procedure to change the database engine in Mysql?
Ans. By using:
ALTER TABLE EnterTableName ENGINE = EnterEngineName;
- What is the default storage engine in MySQL?
Ans. InnoDB is the default storage engine in MySQL.
- What is COALESCE?
Ans. COALESCE returns the first non-NULL expression within its arguments from more than one column in the arguments.
The syntax for COALESCE is –
COALESCE (expression 1, expression 2, … expression n)
- What syntax is used to create an index in MySQL?
Ans. By using-
CREATE INDEX [index name] ON [table name]([column name]);
- What are the different storage engines/table types present in MySQL?
Ans. MySQL supports two types of tables: transaction-safe tables (InnoDB and BDB) and non-transaction-safe tables (HEAP, ISAM, MERGE, and MyISAM).
- MyISAM: This is a default table type that is based on the Indexed Sequential Access Method (ISAM). It extends the former ISAM storage engine. These tables are optimized for compression and speed.
- HEAP: It allows fast data access. However, the data will be lost if there is a crash. HEAP table cannot have BLOB, TEXT, and AUTO_INCREMENT fields.
- BDB: It supports transactions using COMMIT and ROLLBACK. It is slower than the others.
- InnoDB: These tables fully support ACID-compliant and transactions.
- MERGE: Also known as the MRG_MyISAM engine, MERGE is a virtual table that combines multiple MyISAM tables that have a similar structure to one table.
- What are the differences between and MyISAM and InnoDB?
Ans. The following are the differences between and MyISAM and InnoDB
MyISAM | InnoDB |
No longer supports transactions | Supports transactions |
It supports Table-level Locking | It helps in Row-level Locking |
No longer assist ACID (Atomicity, Consistency, Isolation, and Durability) | Supports ACID property |
Supports FULLTEXT index | Does not support FULLTEXT index |
- What drivers are available in MySQL?
Ans. Below are the drivers available in MySQL:
- PHP Driver
- C WRAPPER
- ODBC Driver
- JDBC Driver
- PYTHON Driver
- RUBY Driver
- PERL Driver
- CAP11PHP Driver
- Ado.net5.mxj
- What is a Join? What are the different types of joins in MySQL?
Ans. Join is a query that retrieves related columns or rows. There are four types of joins in MySQL:
- Inner Join – it returns the rows if there is at least one match in two tables.
- Left Join – returns all the rows from the left table even if there is no match in the right table.
- Right Join – returns all the rows from the right table even if no matches exist in the left table.
- Full Join – would return rows when there is at least one match in the tables.
- What is a pattern matching operator in SQL?
Ans. The pattern matching operator in SQL allows you to perform pattern search in data if you have no clue as to what that word should be. Rather than writing the exact word, this operator uses wildcards to match a string pattern. The LIKE operator is used with SQL Wildcards to get the required information.
LIKE operator is used for pattern matching in the below format:
- % – It matches zero or more characters.
For Example – To search for any employee in the database with the last name beginning with the letter A
SELECT *
FROM employees
WHERE last_name LIKE ‘A%’
- _ (Underscore) – it matches exactly one character.
For Example – This example matches only if A appears at the third position of the last name
SELECT *
FROM employees
WHERE last_name LIKE ‘_ _A%’
- What is a Stored Procedure? What are its advantages and disadvantages?
Ans. A Stored Procedure is an SQL function that consists of several SQL statements to access the database system. It can be stored for later use and can be used many times. If you have to perform a particular task, repeatedly, you won’t have to write the statements repeatedly, you will just have to call the stored procedure. This saves time and avoids writing code again.
Syntax: To create a stored procedure
CREATE PROCEDURE procedure_name
AS
sql_statement
GO;
Syntax: To execute a stored procedure
EXEC procedure_name;
Advantages of Stored Procedure:
- Execution becomes fast and efficient as stored procedures are compiled once and stored in executable form.
- A Stored Procedure can be used as modular programming. Once created and stored, it can be called repeatedly, whenever required.
- Maintaining a procedure on a server is easier than maintaining copies on different client machines.
- Better security.
Disadvantages of Stored Procedure:
- It can be executed only in the database and utilizes more memory in the database server.
- Any data errors in handling stored procedures are not generated until runtime.
- Version control is not supported.
- Explain the STUFF and REPLACE functions.
Ans. This is one of the commonly asked SQL interview questions.
The STUFF function deletes a substring of a certain length of a string and replaces it with a new string. It inserts the string at a given position and deletes the number of characters specified from the original string.
Syntax:
STUFF (string_expression, start, length, replacement_string)
Parameters:
- string_expression: the main string in which the stuff is to be applied.
- start: starting position of the character in string_expression.
- length: length of characters that need to be replaced.
- replacement_string: new string that is to be applied to the main string.
The REPLACE functionreplaces all occurrences of a specific string value with another string.
Syntax:
REPLACE (string_expression, search_string, replacement_string)
Parameters:
- string_expression: the main string that contains the substring to be replaced.
- Search_string: to locate the substring.
- replacement_string: the new replacement string.
- What is a Database Cursor?
Ans. A database cursor is a mechanism that allows for traversal over the records in a database. Cursors also allow processing after traversal, like retrieval, addition, and deletion of database records. A cursor is behaviorally similar to the programming language iterator.
How to use a Database Cursor in SQL Procedures
- Declare variables.
- Declare a cursor that defines a result set. The cursor declaration must always be associated with a SELECT Statement.
- Open the cursor to initialize the result set.
- FETCH statement to retrieve and move to the next row in the result set.
- Close the cursor.
- Deallocate the cursor.
- What are SQL Scalar functions? Name some.
Ans. An SQL scalar function returns a single value based on the user input. Below are some of the commonly used scalar functions:
SQL Scalar Function | Format | Description |
LCASE() | SELECT LCASE(column_name) FROM table_name; | converts the value of a field to lowercase |
UCASE() | SELECT UCASE(column_name) FROM table_name; | converts the value of a field to uppercase |
LEN() | SELECT LENGTH(column_name) FROM table_name; | returns the total length of the value in a text field |
ROUND() | SELECT ROUND(column_name,decimals) FROM table_name; | rounds a numeric field to the number of decimals specified |
NOW() | SELECT NOW() FROM table_name; | returns the current system data and time |
FORMAT() | SELECT FORMAT(column_name,format) FROM table_name; | sets the format to display a collection of values |
- What is the difference between SQL and PL/SQL?
Ans. This is an important question that you must prepare for your SQL interview.
Below are some of the major differences between SQL and PL/SQL:
SQL | PL/SQL |
SQL is a database Structured Query Language. | PL/SQL or Procedural Language/Structured Query Language is a database programming language using SQL. It is a dialect of SQL to enhance SQL capabilities. |
It was developed by IBM Corporations and first appeared in 1974. | It was developed by Oracle Corporation in the early 90s. |
Data variables are not available. | Data variables are available. |
SQL is a declarative language. | PL/SQL is a procedural language. |
It is data-oriented. | PL/SQL is application-oriented. |
It can execute only a single query at a time. | It can execute a whole block of code at a time. |
SQL can directly interact with the database server. | PL/SQL cannot directly interact with the database server. |
It can be embedded in PL/SQL. | It cannot be embedded in SQL. |
SQL used to write queries, DDL, and DML statements. | It is used to write program blocks, functions, procedures triggers, and packages |
SQL acts as the source of data that is to be displayed. | PL/SQL acts as a platform where SQL data will be displayed. |