Quality Thought SQL Tutorial
Quality Thought SQL Tutorial
Advantages:
Available Databases: SQL Server, Oracle, Teradata, MySQL, MS-Access, DB2, Sybase, Fox Pro, Ingres
sql, PostgreSQL, etc.,
Database Objects: Tables, Stored Procedures, Cursors, Views, Triggers, Functions, Indexes,
Synonyms, User Defined Types, Cubes, etc.,
Among the above database objects, Table has structure and Data. Remaining are used to
implement functionality and business logic.
SQL: Structured Query Language. SQL is the database language used to perform certain
operations on the database.
DDL: Data Definition Language actually consists of the SQL commands that can be used to define
the database schema. It simply deals with descriptions of the database schema and is used to create
and modify the structure of database objects in the database. DDL is a set of SQL commands used
to create, modify, and delete database structures but not data. These commands are normally not
used by a general user, who should be accessing the database via an application.
CREATE: This command is used to create the database or its objects (like table, index,
function, views, store procedure, and triggers).
TRUNCATE: This is used to remove all records from a table, including all spaces allocated for
the records are removed.
DML: The SQL commands that deal with the manipulation of data present in the database belong
to DML or Data Manipulation Language and this includes most of the SQL statements.
DRL: DRL is a component of SQL statement that allows getting data from the database and imposing
order upon it. It includes the SELECT statement. This command allows getting the data out of the
database to perform operations with it. When a SELECT is fired against a table or tables the result is
compiled into a further temporary table, which is displayed or perhaps received by the program i.e.
a front-end.
DCL: DCL commands mainly deal with rights, permissions, and other controls of the database system.
REVOKE: This command withdraws the user’s access privileges given by using the GRANT
command.
TCL: TCL commands deal with the transaction within the database.
Data Types:
data type is a guideline for SQL to understand what type of data is expected inside of each
column, and it also identifies how SQL will interact with the stored data.
1. Type of data
2. Size of the memory it occupies.
DDL Commands:
Create: This is the command useful to create any database object like Table, Database,
Trigger, etc.
Create:
Table creation syntax: create table <table name> (col1 datatype, col2, datatype ,…,coln
datatype)
Col specifies the name of the column and data type specifies the type of data that the
column can hold
Ex: create table employee (eid int, ename varchar (20), salary money, age int, gender char
(1), did int)
Alter: This is the command useful to modify the database object structure like adding a new
column, deleting existing column, changing the datatype of the column.
Adding new column to existing table syntax: alter table <table name> add <col_name>
<data type>
Removing existing column from table syntax: alter table <table_name> drop <col name>
Changing the datatype of existing column syntax: alter table <table name> alter <col
name><datatype>
Drop: This statement is used to drop an existing table in a database. This will remove table
data as well as table definition
Note: Be careful before dropping a table. Deleting a table will result in loss of complete
information stored in the table
DML Commands:
Insert: Insert command is used to insert records into a table. THis can be done in two ways.
Note: The columns for which data is not available will be inserted with ‘NULL’
Note: Be careful when updating records in a table! Notice the WHERE clause in the UPDATE
statement. The WHERE clause specifies which record(s) that should be updated. If we omit the
WHERE clause, all records in the table will be updated
Delete: Delete command is used to delete existing records from the table
Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE
statement. The WHERE clause specifies which record(s) should be deleted. If we omit the WHERE
clause, all records in the table will be deleted
Truncate: Truncate command is used to data inside the table but not the table definition
DRL Commands:
Select: Select command is used to retrieve information from the database objects.
Using select it is possible to retrieve all the columns data or the specific column(s) data
Group By: The GROUP BY statement groups rows that have the same values into summary
rows, like "find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(),
SUM(), AVG()) to group the result-set by one or more columns
Having: Having is used to apply condition on the result set of group by query.
Ex: select count(*) from emp group by did having count(*) > 1
Arithmetic Operators: +, -, *, /, %
DATEADD() It will display the date and time by add or subtract date and time interval.
Syntax − DATEADD(datepart, number, datecolumnname)
Select dateadd(day, 10, getdate()) as after10daysdatetimefromcurrentdatetime
DATEDIFF() It will display the date and time between two dates.
Syntax − DATEDIFF(datepart, startdate, enddate)
Select datediff(hour, 2015-11-16, 2015-11-11) as
differencehoursbetween20151116and20151111
LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are wildcards often used in conjunction with the LIKE operator. They are:
UNION: The UNION operator is used to combine the result-set of two or more SELECT statements.
Every SELECT statement within UNION must have the same number of columns
The columns must also have similar data types
The columns in every SELECT statement must also be in the same order
UNION
UNION
UNION ALL: The UNION ALL operator is used to combine the result-set of two or more SELECT
statements same as UNION but includes duplicates.
UNION ALL
UNION ALL
INTERSECT: The SQL INTERSECT clause/operator is used to combine two SELECT statements, but
returns rows only from the first SELECT statement that are identical to a row in the second SELECT
statement. This means INTERSECT returns only common rows returned by the two SELECT statements.
Just as with the UNION operator, the same rules apply when using the INTERSECT operator.
MySQL does not support the INTERSECT operator.
INTERSECT
INTERSECT
EXCEPT: The SQL EXCEPT clause/operator is used to combine two SELECT statements and returns rows
from the first SELECT statement that are not returned by the second SELECT statement. This means
EXCEPT returns only rows, which are not available in the second SELECT statement.
Just as with the UNION operator, the same rules apply when using the EXCEPT operator.
MySQL does not support the EXCEPT operator.
EXCEPT
EXCEPT
JOINS:
Join is used to retrieve information from two or more tables based on a common column
between them.
LEFT OUTER JOIN: Returns all records from the left table, and the
matched records from the right table
RIGHT OUTER JOIN: Returns all records from the right table,
and the matched records from the left table
SELF JOIN: Returns records by joining the table with itself. Alias is used for self-join
Sub Queries: A Subquery or Inner query or a Nested query is a query within another SQL query. A
subquery is used to return data that will be used in the main query as a condition to further restrict
the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with
the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
Ex: select * from emp where did = (select did from dept where dname = ‘HR’)
Backup Tables:
1. Backup table definition is not available, create a table and insert the data
2. Backup table definition is available, insert data into existing backup table
Select * Into: This is used to create the table and insert the data
Insert into select: This is used to insert data into existing table
Constraints: Constraints are used to specify rules for data in a table. Constraints are used to limit the
type of data that can go into a table. This ensures the accuracy and reliability of the data in the
table. If there is any violation between the constraint and the data action, the action is aborted.
1. Primary Key: It will not allow duplicate values, nulls. Only one primary key per table is
allowed.
6. Foreign Key:(Referential Integrity) Foreign Key column of primary table should be the
primary key column of the referencing table
Syntax: <col name><data type> foreign key references <table name>(<col name>)
7. Composite Primary Key: Primary key will be applied on the combination of columns.
Ex: create table dept (did int primary key, dname varchar(10))
Views: view is a virtual table based on the result-set of an SQL statement. View contains rows and
columns, similar to a table. A view can be created from one or more tables in a database.
View returns the updated data every time as it recreates the view every execution.
Creation of a view:
Syntax: create view view_name as select col_list from table_name where [condition]
Deleting a view:
Note: Insert, Update and Delete manipulations can be done on views. The manipulation will
be impacted on the original table.
Indexes: Indexes are used to speed up the retrieval of data from the database. Best practice is
creating indexes on the columns that will be frequently used from searching. Why because, updating
the table with indexes will take more time than updating tables without indexes as the indexes also
need to be updated.
Types of Indexes:
3. Implicit Index: Default index will be created on table columns of primary key and unique
4. Index: It will allow duplicates.
Normalization: Normalization is the process of organizing data in a database. This includes creating
tables and establishing relationships between those tables according to rules designed both to
protect the data and to make the database more flexible by eliminating redundancy and
inconsistent dependency.
Create separate tables for sets of values that apply to multiple records.
Relate these tables with a foreign key.
Pros of Denormalization:
Queries to retrieve can be simpler (and therefore less likely to have bugs), since we need to
look at fewer tables.
Cons of Denormalization:
Data may be inconsistent. Which is the “correct” value for a piece of data?
Ans: SQL server can be connected to any database which has an OLE-DB provider to give a
link. Example: Oracle has an OLE-DB provider which has a link to connect with the SQL server
group.
4. What is a subquery?
Ans: A subquery is a query which can be nested inside a main query like Select, Update, Insert
or Delete statements. This can be used when expression is allowed.
A sub query should be placed in the right hand side of the comparison operator of
the main query
A subquery should be enclosed in parenthesis because it needs to be executed first
before the main query
More than one subquery can be included
5. What is a Trigger?
Ans: Triggers are used to execute a batch of SQL code when insert or update or delete
commands are executed against a table. Triggers are automatically triggered or executed
when the data is modified
6. Types of Triggers
Ans:
Insert
Delete
Update
Instead of
7. What is Identity?
Ans: IDENTITY column is used in table columns to make that column as Auto increment
number
Ans: Every statement between BEGIN and COMMIT becomes persistent to the database
when the COMMIT is executed. Every statement between BEGIN and ROLLBACK are reverted
to the state when the ROLLBACK was executed
11. How can data be copied from one table to another table?
Ans: INSERT INTO SELECT: This command is used to insert data into a table which is already
created.
Ex: Insert into <new table name> select * from <old table name>
SELECT INTO: This command is used to create a new table and its structure and data can be
copied from existing table
Ex: select * into <new table name> from <old table name>
FROM emp
(OR)
Ans:
When salary values are unique: select top 1 * from (select top 4 * from emp order by
salary desc) temp order by salary asc
When salary values are having duplicates: select * from emp where salary = (select
top 1 * from (select top 3 * from (select distinct(salary) from emp ) temp1 order by
salary desc) temp2 order by salary asc)
Ans: SQL constraints are a set of rules or conditions implemented on an RDBMS to specify
what data can be inserted, updated, or deleted in its tables. This is done to maintain data
integrity and ensure that the information stored in database tables is accurate.
Ans: An SQL index stores important parts of a database table to allow for a quick and
efficient lookup. Rather than searching the entire database, users only have to consult the
index during data retrieval. Indexes, therefore, help improve performance in an RDBMS
Ans: Aliases are temporary names given to tables or columns for the duration of a particular
SQL query
Ans: Normalization is the process of dividing data into tables to remove redundant data
and improve data integrity.
Denormalization is used to combine multiple tables in order to reduce the time required to
perform queries.
Ans:
Delete Truncate
The DELETE command is used to delete While this command is used to delete all the rows from a
specific rows(one or more). table.
The DELETE statement removes rows one TRUNCATE TABLE removes the data by deallocating the
at a time and records an entry in the data pages used to store the table data and records
transaction log for each deleted row. only the page deallocations in the transaction log.
The DELETE command is slower than the While the TRUNCATE command is faster than the DELETE
TRUNCATE command. command.
21. Write a query to get the count of employees from each department?
22. Write a query to get the duplicate employee records from each department
Ans: select Deptid, count(*) as No_of_Employees from emp group by deptid having
No_of_Employees > 1
23. Write a query to list all the employees whose name starts with ‘A’
24. write a query to list all the employees whose name starts with ‘A’ and ends with ‘N’
25. Write a query to list all the employees whose name start with ‘A’ and ends with ‘N’ and 2
characters in between
Ans: select * from emp where ename like ‘A__N’ (Two underscores between A and N)
offset 1 rows