Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

SQL

Download as pdf or txt
Download as pdf or txt
You are on page 1of 64

SQL

For database management systems there are


special kinds of languages called query language
that can be used to access and manipulate data
from the database. The Structured Query Language
(SQL) is the most popular query language used by
major relational database management systems
such as MySQL, ORACLE, SQL Server, etc.
SQL
● SQL stands for Structured Query Language.
● It is used to create, transform and retrieve
information from Relational Database
Management System.
● It also creates an interface between the user and the
database.
DIFFERENCE BETWEEN SQL AND MYSQL
SQL is a query language, whereas MySQL is a
relational database that uses SQL to query a
database. You can use SQL to access, update, and
manipulate the data stored in a database.
SQL is used for writing queries for
databases, MySQL facilitates data storing,
modifying, and management in a tabular format.
Installing MySQL
MySQL is an open source RDBMS software which can be easily downloaded from
the official website https:// dev.mysql.com/downloads. After installing MySQL,
start MySQL service. The appearance of mysql> prompt (Figure 9.1) means that
MySQL is ready to accept SQL statements.
Following are some important points to be kept in mind while using
SQL:

• SQL is case insensitive. For example, the column


names ‘salary’ and ‘SALARY’ are the same for SQL.
• Always end SQL statements with a semicolon (;).
• To enter multiline SQL statements, we don’t write “;”
after the first line. We press the Enter key to continue on
the next line.
The prompt mysql> then changes to “->”, indicating that
statement is continued to the next line.
After the last line, put “;” and press enter.
TYPES OF SQL COMMANDS
1. Data Definition Language (DDL)
2. Data Manipulation Language(DML)
3. Data Control Language(DCL)
4. Transaction Control Language(TCL)
Types of SQL Commands
 DDL (Data Definition Language)
To create database and table structure-commands like CREATE , ALTER , DROP
etc.

DML (Data Manipulation Language) Record/rows related


operations.commands like SELECT...., INSERT..., DELETE..., UPDATE....
etc.

 DCL (Data Control Language)


used to manipulate permissions or access rights to the tables.
commands like GRANT , REVOKE etc.

 Transactional control Language.


Used to control the transactions.commands like COMMIT, ROLLBACK,
SAVEPOINT etc.
1. Data Definition Language (DDL)Commands
❏ These commands define the database structure and its related
operations.
❏ It is used to create and modify the structure of database objects in
database.
❏ Example of DDL commands in SQL are:
❏ CREATE – Create an object. ...
❏ DROP – This SQL DDL command helps to delete objects. ...
❏ ALTER – Used to alter the existing database or its object
structures.
❏ TRUNCATE – This SQL DDL command removes records from
tables.
❏ RENAME – Renaming the database objects.
Data Manipulation Language(DML) Commands

It is used to retrieve, store, modify, delete, insert and update data in


database.
Examples of DML commands in SQL are:
SELECT - To extract information from the table.
UPDATE - To modify or change the data in a table.
INSERT - To insert new data into a table.
DELETE - To delete data(tuple)from a table.
Differentiate between DDL and DML Commands

DDL DML
1.These commands allow us to 1.These commands are used to
perform tasks related to Data manipulate the data ie. records or
definition ie. related to the rows in a table.
structure of the database.
2.Examples of these commands 2. Examples of these commands
are : CREATE, ALTER , DROP are : INSERT , UPDATE , DELETE ,
,RENAME , USE. SELECT .
Data type of Attribute

Data type of an attribute indicates the type of data


value that an attribute can have. It also decides the
operations that can be performed on the data of that
attribute. For example, arithmetic operations can be
performed on numeric data but not on character data.
Commonly used data types in MySQL are numeric
types, date and time types, and string types.
SQL DATATYPES
Data type Description
CHAR(n) Specifies character type data of length n where n could be any value from 0 to 255.
CHAR is of fixed length, means, declaring CHAR (10) implies to reserve spaces for 10
characters. If data does not have 10 characters (e.g., ‘city’ has four characters), MySQL
fills the remaining 6 characters with spaces padded on the right.
VARCHAR(n) Specifies character type data of length where n could be any value from 0 to 65535. But
unlike CHAR, VARCHAR(n) is a variable-length data type. That is, declaring VARCHAR
(30) means a maximum of 30 characters can be stored but the actual allocated bytes
will depend on the length of entered string. So ‘city’ in VARCHAR (30) will occupy
space needed to store 4 characters only.
INT INT specifies an integer value. Each INT value occupies 4 bytes of storage. The range of
unsigned values allowed in a 4 byte integer type are 0 to 4,294,967,295. For values larger
than that, we have to use BIGINT, which occupies 8 bytes.
FLOAT Holds numbers with decimal points. Each FLOAT value occupies 4 bytes.
DATE The DATE type is used for dates in 'YYYY-MM-DD' format. YYYY is the 4 digit year, MM
is the 2 digit month and DD is the 2 digit date. The supported range is '1000-01-01' to
'9999-12-31'.
Differentiate between CHAR and VARCHAR

CHAR(x) VARCHAR(x)
1.It provides a fixed length memory 1.It DOES NOT provide a fixed length
storage. memory storage.

2.This takes X characters of storage , 2. This will take the actual number of
even if you enter less than x characters. characters entered in the column.

3.If a value is less than than its length x, 3.No blanks are added if the length is
then blanks are added. shorter than the maximum length.
Constraints
Constraints are the certain types of restrictions on the data values that an attribute can
have. Table below lists some of the commonly used constraints in SQL. They are used
to ensure correctness of data. However, it is not mandatory to define constraints for
each attribute of a table.
Constraint Description
NOT NULL Ensures that a column cannot have NULL values where NULL means missing/
unknown/not applicable value.
UN I QUE Ensures that all the values in a column are distinct/unique
DEFAULT A default value specified for the column if no value is provided
PR I MARY KEY The column which can uniquely identify each row/record in a table.
FORE I GN KEY The column which refers to value of an attribute defined as primary key in another
table
CREATE Database
To create a database called Student Attendance , we will type the
following command at mysql prompt
mysql> CREATE DATABASE Student , Attendance ;
Query OK , 1 r ow affected ( 0 . 02 s ec )
A DBMS can manage multiple databases on one computer. Therefore,
we need to select the database that we want to use. To know the
names of existing databases, we use the statement SHOW DATABASES.
From the listed databases, we can select the database to be used. Once
the database is selected, we can proceed with creating tables or
querying data.
.
CREATE Database
The show tables statement that lists names of all the tables within a database.
my s q l > SHOW TABLES ;
Emp t y s e t ( 0 . 06 s ec )
Database Commands in MySql
Getting a list of available databases
mysql> SHOW DATABASES;

Creating a database
mysql> CREATE database myschool;

Deleting a database
mysql> DROP database <databasename>;

To remove table
mysql> drop table <tablename>;
After database creation we can open the database using USE
command
mysql> USE myschool;

To show list of tables in opened database


mysql> SHOW TABLES;

Creating a table in the database is achieved with CREATE table


statement.
mysql> CREATE TABLE student (lastname varchar(15),firstname
varchar(15), city varchar(20), class char(2));
The command DESCRIBE is used to view the structure of a table.
mysql> DESCRIBE student;
Database Commands in MySql
To insert new rows into an existing table use the INSERT command:
mysql>INSERT INTO student
values(‘dwivedi’,’freya’,’Udaipur’,’4’);
We can insert record with specific columns only
mysql>insertintotudent(lastname,
firstname,city)values(‘dwivedi’,’mohak’,’udaipur’,);
With the SELECT command we can retrieve previously
inserted rows:

A general form of SELECT is:

SELECT what to select(field name)


FROM table(s)
WHERE condition that the data must satisfy;
Comparison operators are: < ; <= ; = ; != or <> ; >= ; >
Logical operators are: AND ; OR ; NOT
Comparison operator for special value NULL:
IS mysql> SELECT * FROM student;
Database Commands in MySql
Selecting rows by using the WHERE clause in the SELECT command
mysql> SELECT * FROM student WHERE class=“4";
Selecting specific columns(Projection) by listing their names
mysql> SELECT first_name, class FROM student;
Selecting rows with null values in specific column
mysql> SELECT * FROM Student WHERE City IS NULL ;
BETWEEN- to access data in specified range
mysql> SELECT * FROM Student WHERE class between 4 and
6;
IN- operator allows us to easily test if the expression in the list of values.
mysql> SELECT * FROM Student WHERE class in (4,5,6);
Use of not equal (!=) to operator
Database Commands in MySql
Pattern Matching – LIKE Operator
A string pattern can be used in SQL using the following wild card
% Represents a substring in any length
_ Represents a single character Example:
‘A%’ represents any string starting with ‘A’ character.
‘_ _A’ represents any 3 character string ending with ‘A’. ‘_B%’
represents any string having second character ‘B’ ‘_ _ _’ represents
any 3 letter string.
A pattern is case sensitive and can be used with LIKE operator.
mysql> SELECT * FROM Student WHERE Name LIKE ‘A%’;
mysql> SELECT * FROM Student WHERE Name LIKE ’%Singh%’;
mysql> SELECT Name, City FROM Student WHERE Class>=8 AND Name LIKE
‘%Kumar%’ ;
Database Commands in MySql

Altering Table
The SQL ALTER TABLE command is used to add, delete or modify columns
in an existing table. You should also use the ALTER TABLE command to add
and drop various constraints on an existing table.
Syntax
The basic syntax of an ALTER TABLE command to add a New Column in
an existing table is as follows.
ALTER TABLE table_name ADD column_name datatype;
The basic syntax of an ALTER TABLE command to DROP COLUMN in an
existing table is as follows.
ALTER TABLE table_name DROP COLUMN column_name;
The basic syntax of an ALTER TABLE command to change the DATA TYPE
of a column in a table is as follows.
ALTER TABLE table_name MODIFY COLUMN column_name datatype;
MySQL Order by – e.g.Suppose we are having student table with following data.

Now we write the query – select * from student order by class;

Query result will be in ascending order of class.If we not specify asc/desc in


query then ascending clause is applied by default
Database Commands in MySql
TO arrange the data in a column in ascending/descending order
mysql> SELECT * FROM Student ORDER BY class;

To get descending order use DESC key word.


mysql> SELECT * FROM Student ORDER BY class DESC;
To display data after removal of duplicate values from specific column.
mysql> select distinct class from student;

Deleting selected rows from a table using the DELETE command


mysql> DELETE FROM student WHERE firstname=“amar";
To modify or update entries in the table use the UPDATE command
mysql> UPDATE student SET class=“V" WHERE firstname=“freya";
Database Commands in MySql -Creating Table with Constraints

The following constraints are commonly used in SQL:


NOT NULL -It Ensures that a column cannot have a NULL value
UNIQUE - It Ensures that all values in a column are different
PRIMARY KEY - A combination of a NOT NULL and
UNIQUE. Uniquely identifies each row in a table
FOREIGN KEY - It Uniquely identifies a row/record in another table
CHECK - It Ensures that all values in a column satisfies a specific
condition
DEFAULT - It Sets a default value for a column when no value is specified
INDEX - It is Used to create and retrieve data from the database very
quickly
Database Commands in MySql Creating Table with Constraints
mysql> CREATE TABLE Persons (
ID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
City varchar(255) DEFAULT ‘Jaipur',
CONSTRAINT CHK_Person CHECK (Age>=18) );

mysql> CREATE TABLE Orders ( OrderID int NOT


NULL, OrderNumber int NOT NULL, PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(ID) );
Data Constraint
● Sometimes we put certain restrictions or limitations on
the type of data that can be inserted in one or more
columns of a table. This is done by specifying one or
more constraints on that column(s) while creating the
tables.
● For example, one can define the constraint that the
column mobile number can only have non-negative
integer values of exactly 10 digits. Since each student
shall have one unique roll number, we can put the NOT
NULL and UNIQUE constraints on the RollNumber
column.
● Constraints are used to ensure accuracy and reliability
of data in the database.
Altering Table
ALTER TABLE table_name
DROP INDEX MyUniqueConstraint;
The basic syntax of an ALTER TABLE command to DROP
PRIMARY KEY constraint from a table is as follows.

ALTER TABLE table_name


DROP CONSTRAINT MyPrimaryKey;
If we are using MySQL, the code is as follows −

ALTER TABLE
table_name DROP
PRIMARY KEY;
AGGREGATE FUNCTIONS
An aggregate function performs a calculation on multiple values and returns a
single value. For example, you can use the AVG() aggregate function that takes
multiple numbers and returns the average value of the numbers.Following is the list
of aggregate functions supported by mysql.
Name Purpose

SUM() Returns the sum of given column.


MIN() Returns the minimum value in the given column.
MAX() Returns the maximum value in the given column.
AVG() Returns the Average value of the given column.
COUNT() Returns the total number of values/ records as per given
column.
GROUP BY CLAUSE
● The GROUP BY clause groups a set of rows/records into a set of
summary rows/records by values of columns or expressions. It returns
one row for each group.
● We often use the GROUP BY clause with aggregate functions such as
SUM, AVG, MAX, MIN, and COUNT. The aggregate function that
appears in the SELECT clause provides information about each group.
● The GROUP BY clause is an optional clause of the SELECT
statement.
● Syntax –
● SELECT 1, c2,..., cn, aggregate_function(ci)
● FROM table WHERE where_conditions GROUP BY c1 ,
c2,...,cn; Here c1,c2,ci,cn are column name
MySQL group by – e.g. Suppose we are having student table with following data.

Now we write query–select class from student group by class;

Query result will be unique occurrences of class values,just similar to


use distinct clause like(select distinct class from student).
MySQL GROUP BY with aggregate functions
The aggregate functions allow us to perform the calculation of a set of rows and return a single
value. The GROUP BY clause is often used with an aggregate function to perform calculation
and return a single value for each subgroup.
For example, if we want to know the number of student in each class, you can use the
COUNT function with the GROUP BY clause as follows:Suppose we are having
student table with following data.

Now we write query–select class,count(*) from student group by class;

Query result will be unique occurrences of class values along with counting of students(records)
of each class(sub group).
MySQL GROUP BY with aggregate functions
we are having student table with following data.

Now we write query–select class,avg(marks) from student group by class;

Query result will be unique occurrences of class values along with average
marks of each class(sub group).
MySQL GROUP BY with aggregate functions (with where and order by clause)
we are having student table with following data.

Now we write query–


>>select class,avg(marks) from student where class<10 group by class order by marks desc;

Query result will be unique occurrences of class values where class<10 along with
average marks of each class(sub group) and descending ofer of marks.
Renaming of columns(ALIAS)
In case we want to rename any column while
displaying the output, it can be done by using the
alias 'AS'. The following query selects Employee
name as Name in the output for all the employees:
mysql> SELECT EName as Name FROM EMPLOYEE;
Note: If an aliased column name has space as in the
case of DATE OF BIRTH, it should be enclosed in
quotes as’DATE OF BIRTH’.
Calculating the total
THE END

You might also like