Showing posts with label SQL Questions & Answers. Show all posts
Showing posts with label SQL Questions & Answers. Show all posts

SQL frequently used commands and interview question and answers

Below are the continuous post for the frequently used commands and interview questions for SQL basic and intermediate level SQL Developers, Administrators, and Testers. These questions are about SELECT commands and some of the important and frequently  used commands.


21) What are the privileges that can be granted on a table by a user to others?
Insert, update, delete, select, references, index, execute, alter, all.

22) Which function is used to find the largest integer less than or equal to a specific value?
FLOOR.

23) Which is the subset of SQL commands used to manipulate Oracle Database structures, including tables?
Data Definition Language (DDL).

24) What is the use of DESC in SQL?
DESC has two purposes. It is used to describe a schema as well as to retrieve rows from table in descending order.
Explanation : The query SELECT * FROM EMP ORDER BY ENAME DESC will display the output sorted on ENAME in descending order.

25) What command is used to create a table by copying the structure of another table?
CREATE TABLE .. AS SELECTcommand
Explanation: To copy only the structure, the WHERE clause of the SELECT command should contain a FALSE statement as in the following.
CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE 1=2;
If the WHERE condition is true, then all the rows or rows satisfying the condition will be copied to the new table.

26) What is the output of the following query SELECT TRUNC(1234.5678,-2) FROM DUAL;?
1200.

27) What are the wildcards used for pattern matching.?
_ for single character substitution
% for multi-character substitution.

28) What's an SQL injection?
SQL Injection is when form data contains an SQL escape sequence and injects a new SQL query to be run.

29) What is difference between TRUNCATE & DELETE?
TRUNCATE commits after deleting entire table i.e., cannot be rolled back. Database triggers do not fire on TRUNCATE.
DELETE allows the filtered deletion. Deleted records can be rolled back or committed. Database triggers fire on DELETE.

30) What is a join? Explain the different types of joins?
Join is a query, which retrieves related columns or rows from multiple tables.
Self Join - Joining the table with itself.
Equi Join - Joining two tables by equating two common columns. Non-Equi Join - Joining two tables by equating two common columns.
Outer Join - Joining two tables in such a way that query can also retrieve rows that do not have corresponding join value in the other table.

31) What is the sub-query?
Sub-query is a query whose return values are used in filtering conditions of the main query.

32) What is correlated sub-query?
Correlated sub-query is a sub-query, which has reference to the main query.

33) Explain CONNECT BY PRIOR?
Retrieves rows in hierarchical order eg. select empno, ename from emp where.

34) Difference between SUBSTR and INSTR?
INSTR (String1, String2 (n, (m)),
INSTR returns the position of the m-th occurrence of the string 2 in string1. The search begins from nth position of string1.
SUBSTR (String1 n, m)
SUBSTR returns a character string of size m in string1, starting from n-th position of string1.

35) Explain UNION, MINUS, UNION ALL and INTERSECT?
INTERSECT - returns all distinct rows selected by both queries.
MINUS - returns all distinct rows selected by the first query but not by the second.
UNION - returns all distinct rows selected by either query
UNION ALL - returns all rows selected by either query,including all duplicates.

36) What is ROWID?
ROWID is a pseudo column attached to each row of a table. It is 18 characters long, blockno, rownumber are the components of ROWID.

37) What is the fastest way of accessing a row in a table?
Using ROWID. CONSTRAINTS

38) What is an integrity constraint?
Integrity constraint is a rule that restricts values to a column in a table.

39) What is referential integrity constraint?
Maintaining data integrity through a set of rules that restrict the values of one or more columns of the tables based on the values of primary key or unique key of the referenced table.

SQL interview questions on Commands, Operations, editing database and tables

Below are the interview questions for SQL basic and intermediate level SQL Developers, Administrators, and Testers. These questions are about Commands, Operations, creating and editing database and tables. 

1) How to fetch data from a Database Table?
Using SELECT Statement, we can fetch data from a Database Table
Syntax:
SELECT column1, column2, columnN FROM table_name;
Or
SELECT * FROM table_name;

2) Explain about IN Operator?
The IN operator implements comparison to a list of values, that is, it tests whether a value matches any value in a list of values. IN comparisons have the following general format:
value-1 [NOT] IN ( value-2 [, value-3] ... )
This comparison tests if value-1 matches value-2 or matches value-3, and so on. It is equivalent to the following logical predicate:
value-1 = value-2 [ OR value-1 = value-3 ] ...

3) Explain about FROM Clause in SQL?
The FROM clause always follows the SELECT clause. It lists the tables accessed by the query. For example,
SELECT * FROM s
When the From List contains multiple tables, commas separate the table names. For example,
SELECT sp.*, city FROM sp, s WHERE sp.sno=s.sno
When the From List has multiple tables, they must be joined together.

4) What is the parameter substitution symbol used with INSERT INTO command?
The parameter substitution symbol used with INSERT INTO command is &.

5) What are the various uses of database triggers?
Database triggers can be used to enforce business rules, to maintain derived values and perform value-based auditing.

6) What is a event handler in sql?
An event handler is a routine that is written to respond to a particular event.

7) What are two methods of retrieving SQL?
The two methods of retrieving SQL are
1-Select
2-using Cursor.


8) What is a synonym? How is it used?
A synonym is used to reference a table or view by another name. The other name can then be written in the application code pointing to test tables in the development stage and to production entities when the code is migrated. The synonym is linked to the AUTHID that created it.

9) What is referential integrity?
Referential integrity refers to the consistency that must be maintained between primary and foreign keys, i.e. every foreign key value must have a corresponding primary key value.

10) Explain the EXPLAIN statement?
The explain statement provides information about the optimizer's choice of access path of the SQL.

11) How is the SUBSTR keyword used in SQL?
SUBSTR is used for string manipulation with column name, first position and string length used as arguments. E.g. SUBSTR (NAME, 1 3) refers to the first three characters in the column NAME.

12) What is the difference between group by and order by?
Group by controls the presentation of the rows, order by controls the presentation of the columns for the results of the SELECT statement.

13) What is a subselect? Is it different from a nested select?
A subselect is a select which works in conjunction with another select. A nested select is a kind of subselect where the inner select passes to the where criteria for the outer select.

14) What is the use of CASCADE CONSTRAINTS?
When this clause is used with the DROP command, a parent table can be dropped even when a child table exists.

15) How do you prevent output from coming to the screen?
The SET option TERMOUT controls output to the screen. Setting TERMOUT OFF turns off screen output. This option can be shortened to TERM.

16) Can Primary key is a Foreign Key on the same table?
Yes, Primary key is a Foreign Key on the same table.

17) How do you execute a host operating system command from within SQL?
By use of the exclamation point “!” (in UNIX and some other OS) or the HOST (HO) command.

18) What is a Cartesian product?
A Cartesian product is the result of an unrestricted join of two or more tables. The result set of a three table Cartesian product will have x * y * z number of rows where x, y, z correspond to the number of rows in each table involved in the join.

19) How can variables be passed to a SQL routine?
By use of the & symbol. For passing in variables the numbers 1-8 can be used (&1, &2,...,&8) to pass the values after the command into the SQL PLUS session. To be prompted for a specific variable, place the ampersanded variable in the code itself: “select * from dba_tables where owner=&owner_name;” . Use of double ampersands tells SQLPLUS to resubstitute the value for each subsequent use of the variable, a single ampersand will cause a reprompt for the value unless an ACCEPT statement is used to get the value from the user.

20) What command is used to get back the privileges offered by the GRANT command?
Revoke command is used to get back the privileges offered by the GRANT command.

21) What are the advantages of procedures?
Advantages of procedures:
  • Loaded once and used many times.
  • Performance better coz all SQL statements are sent in one go from the application to the database.
  • Security (no object privileges are given directly).
  • Invoker's rights possible.
  • Data integrity, productivity.

22) What is Parsing?
Parsing checks syntax, checks privileges, and allocating Private SQL Area.

23) What is Cursor?
Name or handle to a private SQL area where Oracle parses and fetches query results.

24) Is SQL supports Conditional and Loop Statements?
No Basically SQL is a Command based Language, not a procedural  language, but it has Operators and built-in Functions.

SQL frequently used commands and interview questions

Below are the frequently used commands and interview questions for SQL basic and intermediate level SQL Developers, Administrators, and Testers. These questions are about SELECT commands and some of the important and frequently  used commands.

 
1) What are most important DDL Commands in SQL?
CREATE TABLE - creates a new database table
ALTER TABLE - alters (changes) a database table
DROP TABLE - deletes a database table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index

2) What are the Operators used in SELECT statements?
= Equal
<> or != Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range LIKE Search for a pattern

3) How to  INSERT Values into Tables?
INSERT INTO table_name VALUES (value1, value2,....)
INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....)

4) How to Update a Column Name?
UPDATE table_name SET column_name = new_value WHERE column_name = some_value

5) How to Delete Columns, Rows?
Delete a particular column:
DELETE FROM table_name WHERE column_name = some_value
Delete All Rows:
DELETE FROM table_name or DELETE * FROM table_name

6) Give an usage for BETWEEN ... AND?
SELECT column_name FROM table_name WHERE column_name BETWEEN value1 AND value2 The values can be numbers, text, or dates.

7) What is the use of CASCADE CONSTRAINTS?
When this clause is used with the DROP command, a parent table can be dropped even when a child table exists.

8) Why does the following command give a compilation error?
DROP TABLE &TABLE NAME;
Variable names should start with an alphabet. Here the table name starts with an '&' symbol.

9) Which system tables contain information on privileges granted and privileges obtained?
USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD

10) Which system table contains information on constraints on all the tables created?obtained?
USER_CONSTRAINTS.

11) State true or false. EXISTS, SOME, ANY are operators in SQL?
True.

12) What does the following query do?
SELECT SAL + NVL(COMM,0) FROM EMP;?
This displays the total salary of all employees. The null values in the commission column will be replaced by 0 and added to salary.

13) What is the advantage of specifying WITH GRANT OPTION in the GRANT command?
The privilege receiver can further grant the privileges he/she has obtained from the owner to any other user.

14) Which command executes the contents of a specified file?
START or @.

15) Which command displays the SQL command in the SQL buffer, and then executes it?
RUN.

16) What command is used to get back the privileges offered by the GRANT command?
REVOKE.

17) Which date function is used to find the difference between two dates?
MONTHS_BETWEEN.

18) What operator performs pattern matching?
LIKE operator.

19) What is the use of the DROP option in the ALTER TABLE command?
It is used to drop constraints specified on the table.

20) What operator tests column for the absence of data?
IS NULL operator.

SQL interview questions and answers on creating and editing database and tables

Below are the interview questions for SQL basic and intermediate level SQL Developers, Administrators, and Testers. These questions are about Data Definition Language Commands, Operations, creating and editing database and tables. 

1) What are the Data Definition Language Commands and Operations?
Important Data Definition Language Commands
1) Create
2) Alter
3) Drop
4) Truncate
5) Rename

Important Data Definition Language Operations
1) Create a Database
2) Use Database
3) Rename a Database
4) Drop Database
5) Create a Table
6) Rename Table
7) Add a Column to exiting Table
8) Add multiple columns to existing Table
9) Modify an existing column
10) Rename a Column
11) Drop a Column
12) Truncate a Table
13) Drop a Table
Note: The above example is for MS SQL Server. Download and Install MS SQL Server Express Edition (It is Free Edition) and practice SQL Commands and Operations.

2) How to Create a Database?
Syntax:
Create Database databaseName;
Example:
Create Database proddb;

3) How to Select a Database?
Syntax
Use databaseName;
Example:
Use proddb;

4) How to Rename a Database?
Syntax
Alter Database databaseName Modify Name = newdatabseName;
Example:
Alter Database proddb Modify Name = production

5) How to Drop a Database?
Syntax:
Drop Database databaseName;
Example:
Drop Database proddb;

6) How to Create a Table?
Syntax:
Create Table tableName
(
column1_name dataType(size),
column2_name dataType(size),
.
.
.
);
Example:
Create Table Students
(
STID int,
STName char(50),
);

7) How to View Table info
Select * from Students

8) How to View Table Schema
Select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'Students';

9) How to Rename a Table?
Syntax:
EXEC sp_rename 'old_tablename', 'new_tablename';
Example:
EXEC sp_rename 'Students', 'newStudents';

10) How to Add a Column to an existing Table?
Syntax:
Alter Table table_name add column_name dataType(size);
Example:
Alter Table newStudents add City char(50);

11) How to Add multiple columns to an existing Table?
Syntax:
Alter Table table_name add column1_name dataType(size), column2_name dataType(size);
Or
Alter Table table_name add
column1_name dataType(size),
column2_name dataType(size),
.
.;
Example:
Alter Table newStudents add add1 char(100), add2 char(70);
Or
Alter Table newStudents add
add3 char(100),
add4 char(70),
add5 char (100),
phone int;

12) How to Modify an existing column?
Syntax:
Alter Table table_name Alter Column column_name dataType(size);
Example:
Alter Table newStudents Alter Column add1 varchar(150);

13) How to Rename a Column?
Syntax:
EXEC sp_rename 'table_name.old_column_name', 'new_colum_name';
Example:
ExEC sp_rename 'newStudents.phone', 'mobile'

14) How to Drop a Column?
Syntax:
Alter Table table_name Drop Column column_name;
Example:
Alter Table newStudents Drop Column City;

15) How to Truncate a Table?
Truncate Table command is used to delete complete data from an existing table
Syntax:
Truncate Table table_name;
Example:
Truncate Table newStudents;

16) How to Drop a Table?
Drop Table command is used to delete complete Table (Data and Table Structure) from the Database.
Syntax:
Drop Table table_name;
Example:
Drop Table newStudents;

17) How to add new record into a Table?
Using INSERT INTO statement, we can insert new rows
Syntax:
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN)

SQL interview questions and answers for SQL database servers and operators

Below are the interview questions for SQL basic and intermediate level SQL Developers, Administrators, and Testers. These questions are about SQL Database servers, different types of Databases and different types of operators.

1) What is Database Server?
Database Management Systems provide Database server functionality, database server provides database services to other computer programs or computers.

2) What is MS Access?
  • MS Access was launched in 1992 by Microsoft Corporation as part of MS Office. Microsoft Access is entry-level database management software. It is not only an inexpensive but also powerful database for small-scale projects.
  • MS Access uses the Jet database engine which utilizes a specific SQL language dialect (sometimes referred to as Jet SQL).
  • MS Access comes with the professional edition of MS Office package. MS Access is user friendly database management system.

3) What is Oracle?
Oracle is a relational database management system developed by 'Oracle Corporation and launched in 1977. Oracle supports all major Operating systems includes, MS Windows. NetWare, UnixWare, OS/2 and most UNIX flavors.

4) What is MS SQL Server?
MS SQL Server is a Relational Database Management System developed by Microsoft Inc. Its primary query languages are T-SQL and ANSI SQL.

5) What is Sybase?
Sybase is a computer software company , their primary product is Sybase DBMS, which is a relational database management system based upon structured query language.

6) What is MySQL?
  • MySQL is open source Database Management System, developed by Swedish company MySQL AB.
  • MySQL Supports many different platforms including Microsoft Windows, the major Linux distributions, UNIX, and Mac OS X.
  • MySQL has free and paid versions, depending on its usage (non-commercial/commercial) and features. MySQL comes with a very fast, multi-threaded, multi-user, and robust SQL database server.

7) What is DB2?
DB2 is the short name used for DATABASE 2. It is relational database product developed by IBM. in 1983


8) What is DB/400?
It is one of the flavors of IBM DB2

9) What are the categories of operators available in SQL?
  • Arithmetic operators
  • Comparison operators
  • Logical operators

10) What are Arithmetic operators in SQL?
+ (Addition ) Adds values
- (Subtraction) Subtracts Right side value from Left side value
* (Multiplication) Multiplies values on either side of the operator
/ (Division) Divides left hand operand by right hand operand
% (Modulus) Divides left hand operand by right hand operand and returns remainder

11) What are Comparison operators in SQL?
For example x = 1, y= 2
Operator    Example
=             (x = y) is False
!=            (x != y) is True.
<>           (x <> y) is true.
>             (x > y) is False
<             (x < y) is True       
>=           (x >= y) is False
<=           (x <= y) is True
!<            (x !< y) is False
!>            (x !> y) is True.

Note: Comparison Operators return Logical Results

12) What are Logical operators in SQL? 
Operator    Description
--------        -----------
NOT           Returns TRUE if the following condition is FALSE. Returns FALSE if  it is TRUE. 
AND           Returns TRUE if both component conditions are TRUE. Returns FALSE if either is FALSE
OR            Returns TRUE if either component condition is TRUE. Returns FALSE if both are FALSE.

13) What is a Data Relationship and What are they?
Database Relationship is the connection between the tables in a database. There are 4 types of relationships, and they are:
  • One to One Relationship
  • One to Many Relationship
  • Many to One Relationship
  • Many to Many Relationship

14) What are Important Data Types in SQL?
DataType                Syntax
character                   char(x)
integer                        integer
numeric                      numeric(p,s)
decimal                       decimal(p,s)
float                             float(p)
date                             date
time                             time
character varying       varchar2(x)
bit                                bit(x)
real                             real
smallint                       smallint