0% found this document useful (0 votes)
3 views

SQL_Learning_Materials.docx (1)

SQL

Uploaded by

saksham shivhare
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

SQL_Learning_Materials.docx (1)

SQL

Uploaded by

saksham shivhare
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

What is SQL?

SQL is a structured query language. By using this we can manipulate and retrieve the
data in the databases.

Uses of SQL:
● We can create a table
● We can insert values into table
● We can update the table
● Delete the records from the table
● Delete the table
● We can create new databases
● We can retrieve the data from the table based on conditions
● We can set permissions on tables

What is RDBMS?
RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL,
and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and
Microsoft Access.A Relational database management system (RDBMS) is a database
management system (DBMS) that is based on the relational model as introduced by E. F.
Codd. Now we will look at the attributes of RDBMS.

What is a table?
The data in an RDBMS is stored in database objects which are called tables. This table is
basically a collection of related data entries and it consists of numerous columns and
rows.
Remember, a table is the most common and simplest form of data storage in a relational
database. The following program is an example of a CUSTOMERS table

What is a field?
Every table is broken up into smaller entities called fields. The fields in the CUSTOMERS
table consist of ID, NAME, AGE, ADDRESS and SALARY. A field is a column in a table
that is designed to maintain specific information about every record in the table.

What is a Record or a Row?


A record is also called as a row of data is each individual entry that exists in a table. For
example, there are 7 records in the above CUSTOMERS table.

A record is a horizontal entity in a table.

What is a column?
A column is a vertical entity in a table that contains all information associated with a
specific field in a table.
For example, a column in the CUSTOMERS table is ADDRESS, which represents location
description and would be as shown below −

Data Integrity:
The following categories of data integrity exist with each RDBMS −

● Entity Integrity − There are no duplicate rows in a table.


● Domain Integrity − Enforces valid entries for a given column by restricting
the type, the format, or the range of values.
● Referential integrity − Rows cannot be deleted, which are used by other
records.
● User-Defined Integrity − Enforces some specific business rules that do not
fall into entity, domain or referential integrity.
Database Normalization:
Database normalization is the process of efficiently organizing data in a database. There
are two reasons of this normalization process −

● Eliminating redundant data, for example, storing the same data in more
than one table.
● Ensuring data dependencies make sense.

Both these reasons are worthy goals as they reduce the amount of space a database
consumes and ensures that data is logically stored. Normalization consists of a series of
guidelines that help guide you in creating a good database structure.

Normalization guidelines are divided into normal forms; think of a form as the format or
the way a database structure is laid out. The aim of normal forms is to organize the
database structure, so that it complies with the rules of first normal form, then second
normal form and finally the third normal form.

It is your choice to take it further and go to the fourth normal form, fifth normal form
and so on, but in general, the third normal form is more than enough.

● First Normal Form (1NF)


● Second Normal Form (2NF)
● Third Normal Form (3NF)
Data Types in MySQL:
Numeric data types in SQL:

Data Type From To


bigint -9,223,372,036,854,775, 9,223,372,036,854,775,8
808 07

int -2,147,483,648 2,147,483,647

smallint -32,768 32,767

tinyint 0 255

bit 0 1

decimal -10^38 +1 10^38 -1

money -922,337,203,685,477.58 922,337,203,685,477.58


08 07

float -1.79E + 308 1.79E + 308

Date and Time Data Types:

Data Type From To


datetime Jan 1, 1753 with time Dec 31, 9999 with time

smalldatetime Jan 1, 1900 Jun 6, 2079

Date Jan 1, 1753 Dec 31, 9999


Character Strings Data Types:
● char : Maximum length of 8,000 characters.( Fixed length non-Unicode
characters)
● varchar : Maximum of 8,000 characters.(Variable-length non-Unicode data).
● varchar(max) : Maximum length of 2E + 31 characters, Variable-length
non-Unicode data (SQL Server 2005 only).
● text : Variable-length non-Unicode data with a maximum length of 2,147,483,647
characters.
Commands in SQL

● SQL commands are instructions. It is used to communicate with the database. It


is also used to perform specific tasks, functions, and queries of data.
● SQL can perform various tasks like create a table, add data to tables, drop the
table, modify the table, set permission for users.

1. Data Definition Language (DDL):


● DDL changes the structure of the table like creating a table, deleting a table,
altering a table, etc.

● All the commands of DDL are auto-committed, which means it permanently saves
all the changes in the database.
Creating a Database:
The below syntax will help you to create a database named Innomatics.

Dropping a database:
The syntax below will let you drop a database.

Creating a table in SQL:


The below command will help you to create a table

Example:

Creating an employee table:

+
Dropping a table in SQL:

SQL commands for altering a table:

● Command to change the datatype of the column.

Example:

● Command for adding a new column to an existing table:

Adding a new column for email ID.


Command for renaming a column name:
Renaming lastname to ‘lname’.

Inserting values into the created table


Syntax 1:

If in case you are using the below syntax you have to insert the values in the same order
as the columns are created.

Example:

Syntax 2:

we can insert the values into emp_t table:


Updating the records inside the table:
Let’s look at the data in the employee table.

Syntax for updating a record.

Let’s update the salary for employee number 122 to 85000.

We can see that the salary for employeeNumber 122 as been changed to 85000.
Deleting a record inside the table.
Using delete command you can delete a specific record from a table.

Let’s delete a record for employeeNumber 122

We can now see that record for employeeNumber has been deleted
SQL constraints:
● Constraints are used to specify the rules for data in a table.
● constraints are specified at the time of creating the table and also specify after
creating the table using an alter statement.

In SQL we have following constraints


1. NOT NULL - Ensures that a column cannot have a NULL value
2. UNIQUE - Ensures that all values in a column are different
3. PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies
each row in a table
4. FOREIGN KEY - Prevents actions that would destroy links between tables
5. CHECK - Ensures that the values in a column satisfies a specific condition
6. DEFAULT - Sets a default value for a column if no value is specified

Not Null Constraint:


● By default, the column can hold null value. We specify a column with not null
constraint means that column will not allow the null values.
● Once you specify the column as not null that means we cannot insert a new
record or update a record without adding value to this field.

Example1:

In the above example we specify the id column as not null at the time of table creation.
Unique:
The unique constraint ensures that all the values in the table are different

Example:

Check constraint:
If you specify a column with a check constraint , values can only be inserted if the
value satisfies a specific condition.

The following SQL creates a CHECK constraint on the "Cost" column when the table is
created. The CHECK constraint ensures that the cost of product in greater than zero.

Primary key constraint:


The primary key constraint can uniquely identify each record in a table.
Properties of primary key:
1. In table we have only one primary key
2. It should be unique and not null
The following syntax creates a primary key on the id column of emp table.

Foreign Key Constraint:


● First, specify the name of foreign key constraint that you want to create after
the CONSTRAINT keyword. If you omit the constraint name, MySQL
automatically generates a name for the foreign key constraint.
● Second, specify a list of comma-separated foreign key columns after the FOREIGN
KEY keywords. The foreign key name is also optional and is generated
automatically if you skip it.
● Third, specify the parent table followed by a list of comma-separated columns to
which the foreign key columns reference.
● Finally, specify how foreign key maintains the referential integrity between the
child and parent tables by using the ON DELETE and ON UPDATE clauses.
The reference option determines action which MySQL will take when values in
the parent key columns are deleted (ON DELETE) or updated (ON UPDATE).

Syntax for basic foreign key:

MySQL has four reference options: CASCADE, SET NULL, NO ACTION, RESTRICT.

● CASCADE: if a row from the parent table is deleted or updated, the values of the
matching rows in the child table automatically deleted or updated.

● SET NULL: if a row from the parent table is deleted or updated, the values of the
foreign key column (or columns) in the child table are set to NULL.
● RESTRICT: if a row from the parent table has a matching row in the child table,
MySQL rejects deleting or updating rows in the parent table.
● NO ACTION: is the same as RESTRICT.

In fact, MySQL fully supports three actions: RESTRICT, CASCADE and SET NULL.

If you don’t specify the ON DELETE and ON UPDATE clause, the default action
is RESTRICT.

Disabling foreign key checks:


Sometimes, it is very useful to disable foreign key checks e.g., when you import data
from a CSV file into a table. If you don’t disable foreign key checks, you have to load data
into a proper order i.e., you have to load data into parent tables first and then child
tables, which can be tedious. However, if you disable the foreign key checks, you can load
data into tables in any order.
SQL DQL Commands

● Command to fetch all the record from a table

● Where clause:
o If we want to access the particular records that satisfy a particular
condition , we use the where clause.

In the above query we fetch the records where deal size is “SMALL”.

● Operators in SQL:
Operator Description
= Equal to
> Greater than
< Less than
<= Less than equal to
>= Greater than equal to
Between To find value in range
Like Search for a pattern
IN To find values in a list

● The above query will display the records where sales are less than 10000 dollars.

● The above query will display the records where sales are greater than 10000
dollars.
● The above query will display the records where sales are less than or equal to
10000 dollars.

● The above query will display the records where sales is greater than or equal to
dollars.

● The above query will display the records where sales is between the range of
5000 to 6000 dollars.

● The above query will display the records where country is France or USA;

● AND OPERATOR:
And operator will only show the records which satisfy both the conditions

The above query will display the records which have sales greater than 10000 and the
country is USA.

● OR OPERATOR:
The OR operator will display the records if a record satisfies any one of the
conditions which are given.

The above query will display the records which either have sales greater than 10000 or
the country is USA.
● ORDER BY
Order by clause will display the records in a sorted way either in ascending order which
is by default or in descending order.

The above query will sort the sales table in ascending order by sales.

The above query will sort the sales table in descending order by sales.

● GROUP BY:
The GROUP BY clause groups a set of rows into a set of summary rows by values of
columns or expressions. The GROUP BY clause returns one row for each group. In
other words, it reduces the number of rows in the result set.

The above query will show the average of sales for each productline as we have grouped
by productline.
● HAVING CLAUSE:
HAVING Clause is used to filter records from the groups based on the specified
condition.

The above query will show the productlines where total sales is greater than 1000000.

ALIASING:
● If you want to give the temporary name to the table or column we use
aliasing.
● Aliasing is created with “AS” keyword
● Aliasing name exists only during the duration of the query.

STORED PROCEDURE
A stored procedure is a prepared SQL so you can save and that the code we can reused
again and that just called to execute it.

You can pass parameters to a stored procedure so that the stored procedure can act
based on the parameters that are passed.
Now, Let’s create a basic stored procedure to display all the records in the sales table.

SQL JOINS
Joins are mainly used to combine the rows from two or more tables based on a
related column between them.

In SQL we have four types of joins:

1.Inner Join

2. Left Join

3.Right Join

4.Full Join

Inner Join:
Returns records that have matching values in both tables
The above query will give below results.

Left Join:
Returns all records from the left table, and the matched records from the right
table.

The above query will return the result below.


Right Join:
Returns all records from the right table, and the matched records from the
left table.

The above query will return below results.


Self Join:
A self join is a regular join, but the table is joined with itself.
Window Functions in SQL:
A window function performs a calculation across a set of table rows that are somehow
related to the current row. This is comparable to the type of calculation that can be done
with an aggregate function.

There is no official division of the SQL window functions into categories but
nevertheless, they are frequently being divided into two or three types

Rank:

The above query will add a rank column based on the sales made.
Difference between Rank and Dense_rank:
RANK and DENSE_RANK will assign the grades the same rank depending on how they
fall compared to the other values. However, RANK will then skip the next available
ranking value whereas DENSE_RANK would still use the next chronological ranking
value.
Triggers:
Trigger: procedure that starts automatically if specified changes occur to the DBMS

• Three parts:

● Event (activates the trigger)


● Condition (tests whether the triggers should run)
● Action (what happens if the trigger runs)

In the below example we will be creating an After Update Trigger. We will be creating
an employee table and another table employee audit that would log the update done on
the employee table.

This is the employee table and next we will be creating a table that will log the update
made on the employee table.
As of now the employee audit table will be empty as no update has been done. Now, let's
execute one update statement and see the trigger in action.

Below we have the syntax for creating a trigger.

Now let’s see the output for the employee_audit table.

You might also like