Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
86 views

Structured Query Language (SQL)

Structured Query Language (SQL) is a standard language used to create, manipulate and retrieve data from relational databases. SQL has statements for data definition, data manipulation, and data control. It allows users to define tables with columns of different data types, insert records into tables, query data, update records, and control access privileges. Common SQL statements include CREATE, ALTER, DROP, SELECT, INSERT, UPDATE, DELETE, and GRANT.

Uploaded by

Lak Wak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
86 views

Structured Query Language (SQL)

Structured Query Language (SQL) is a standard language used to create, manipulate and retrieve data from relational databases. SQL has statements for data definition, data manipulation, and data control. It allows users to define tables with columns of different data types, insert records into tables, query data, update records, and control access privileges. Common SQL statements include CREATE, ALTER, DROP, SELECT, INSERT, UPDATE, DELETE, and GRANT.

Uploaded by

Lak Wak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Structured Query Language (SQL)

Structured Query Language (SQL) is a standard language for all relational


databases. It is used to create, store, manage, manipulate and retrieve data.

SQL can be used for:


• Creating, altering, and dropping databases and tables.
• Inserting, updating, and deleting records in a table.
• Performing queries or retrieving information from table.
• Granting proper access rights to database and tables.

Main Advantages of using SQL:


1. It is Portable.
2. It has High speed.
3. Simple to learn.
4. Interactive language.
5. Client/Server language.
Types of SQL Statements
Based on their purpose, SQL statements can be broadly classified as:

1. Data Definition Language (DDL) commands


2. Data Manipulation Language (DML)commands

Data Definition Language (DDL) Statements

They are used to define the structure of the database objects i.e. all commands
required to create, modify or remove the existing structure comes under this
category.
For e.g.: DDL commands include CREATE DATABASE, CREATE TABLE, ALTER
TABLE and DROP TABLE.

Data Manipulation Language (DML) Statements

These statements consist of a set of commands which are used to store, access and
manipulate data from existing tables.
For e.g. DML statements include INSERT, SELECT, UPDATE AND DELETE
commands.

Datatypes in MYSQL
Table is the basic entity of any database which is used to store information in rows
and columns. Each attribute/column of a table has a specific datatype.
Datatype refers to the type of value that a particular attribute of a table is
going to hold.
MYSQL offers three main datatypes:

• Numeric
• Date and Time
• String Types.
Let us now discuss them in detail.

Category Data type Description Example

Numeric Int/integer ✓ Used to store integers. ✓ 478


✓ 1245
✓ We can specify a width of
✓ 348
up to 11 digits.
Decimal(M,D) ✓ Used to store number Decimal(6,2) can
with or without fractional store numbers like
part.
✓ 1234.35
✓ ‘M’ represents the
✓ 234.78
Maximum length (Whole
✓ 234.1
part+ decimal places)
and ‘D’ represents the
no. of places after
decimal.
✓ Decimal(6,2) means
maximum 6 digits can be
there with 2 digits after
decimal.

Date Date ✓ Used to store date December 25th,


✓ The valid date formats 1976 would be
are:YYYY-MM-DD or stored as ‘1976-
DD/MON/YY or 12-25’.
YYYY/MM/DD or
MM/DD/YY or DD-MON-
YYYY.
✓ Range is between 1000-
01-01 and 9999-12-31.
✓ Default format is
‘YYYY-MM-DD’

String Char(size) ✓ It is a fixed-length string For e.g. for storing


between 1 to 255 grades of students
characters in length. as ‘O’,’A’,’B’,’C’ in
✓ Because char is a fixed- a table we can
length datatype, the declare datatype
storage size of the char of grade field as
value is always equal to char(1).
the maximum size for this
column.
✓ CHAR DATATYPE should
be used for those fields
where we know in
advance the length of
value being entered in the
field.
✓ Default size is 1
Usage:If we declare a
field Result as Char (4) it
will reserve 4 bytes in a
memory , even if we enter
1 character in it ,rest of the
space will not be released.
Hence, it will result in
wastage of disk space.

Varchar(size) ✓ Varchar is a variable ‘sonika’


length character string ‘agra’
between 1 to 255. ‘Kolkatta’
✓ Because varchar is a ‘female’
variable-length datatype, etc
the storage size of the
varchar value is the
actual length of the data
entered and not the
maximum size for this
column.
Usage: If we declare a field
Name as Varchar (10) it
will reserve 10 bytes in a
memory .

Note: Character and Date values are always enclosed within single quotes

MYSQL Commands

SHOW DATABASES
This command is used to see the list of all the existing databases.
Syntax:
Show databases;

USE DATABASE
Use command is used to open any existing database so that the user can work
inside it.
Syntax:
Use <database name>;
Example:
The above command changes the current database to school.

SHOW TABLES
A database is a storehouse of tables. Show tables command is used to see the list
of tables present inside the current database.
Syntax:
Show tables;

Since, presently we are working in School database, it will display the list of tables
present inside school database.

CREATE DATABASE
Create database command is used to create a new database.
Syntax:
Create database <database name>;
Example:
Let’s create a new database company

CREATE TABLE Command

CREATE TABLE command is used to create a new table inside the database. In this
command we define the complete structure of any table.
The CREATE TABLE command requires:
✓ Name of the table
✓ Names of fields ,their Datatypes and size(if any)
✓ Constraints(if any)

Syntax:
CREATE TABLE<tablename>
(<Fieldname _1> <datatype> [size] [constraints],
<Fieldname_ 2> <datatype> [size] [constraints],
.
.
.
.
.
<Fieldname_ n> <datatype>[size][constraints]
);

Note:
✓ [] means optional arguments.
✓ Every command in MYSQL ends with a semicolon.

Example:
Let’s create the following table:
Table: Student
Column Name Data Type Size
admno Integer 3
firstname Varchar 20
DOB Date
mobileno Varchar 10
Class Integer 2
section Char 1
Marks Decimal 3,1

A new table ‘Student’ will be created inside School database with the above
mentioned fields.

DESC command:

Desc or Describe command is used to see the structure of any existing table.
Syntax:
Desc/Describe <tablename>;
Command:
Till now we have studied different commands how to create a database and tables
inside it. Now let’s learn how we can insert records inside the table.

INSERT INTO (DML Command):

This command is used to insert records /information in the table.

Example:
Let’s insert the following information inside the table student:

admno firstname DOB mobileno Class Section marks

100 Priyanka 2003-01-13 9811245387 11 A 76.5

123 Suman 2006-04-02 8576230122 6 C NULL

201 Madhav 2002-09-18 9711289701 10 D 69

345 Sambav 2000-08-17 9811456781 12 B 92

134 Madhukar 2007-09-09 9711542908 5 B 71

483 Kavya 2007-06-12 9810211345 5 A 53.5


235 Sanvi 2003-10-11 8657320134 9 D 94
METHOD 1
Syntax:
INSERT INTO <table name>
VALUES (value1,value2,value3,….,value_n);
Command:

First record will be inserted in the table.

Method 2(Alternate command)


Syntax:
INSERT INTO <tablename>
[fieldname_1,fieldname_2,......fieldname_n]
VALUES(value1,value2,value3,….,value_n);

Note: [] are Optional arguments

Command:
The above command can also be used to insert the first record in a table.
Subsequently, we can insert all the records in the table using this command.

Inserting values in Specific columns/Fields


Suppose we want to insert a new record with values for specific columns of the
table, the command used will be:

If we see the table, record will be shown like this

Note: The columns for which value is not inserted will get NULL value.

Explicitly Inserting Null value for any column


Null is a term that is used to represent a missing value. Null does not mean ZERO,
BLANK or Space. It means that the value is not available, unassigned or unknown.
Refer second record of the table student.
Marks of Suman are not known, hence we need to enter NULL there.
Command to insert her record will be:

SELECT (DML Command)


After inserting the records in a table we perform queries on it.
This command is used to retrieve/view the information stored inside the MYSQL
table. It is one of the most powerful SQL commands which can be used when we
want to view:
1. All records from the table.
2. Specific fields from the table.
3. Specific records from the table based on some criteria.
4. Both i.e. Specific fields and records from table.

Syntax:

SELECT (*/field list)


FROM <table name>
[WHERE <condition>];

Note:
Where clause is optional and is used to specify criteria.
<condition> is given according to the following syntax
<Fieldname> operator< value>;
Example
SELECT admno, firstname FROM student WHERE class=11;

Fieldname operator value

To Display entire information of the table

Syntax:
SELECT * FROM <table name>;
Example: Display all the information of a table student.

To Display information related to specific fields/columns of the table


Syntax:
SELECT <field list> FROM <table name>;

Example: Display name and marks of all students from table Student.

To Display specific records from the table (use of where clause)


Syntax:
SELECT *
FROM <table name>
[WHERE <condition>];
Example: Display all information of 11th class students.
To Display specific fields and records from table
Syntax:
SELECT< field list>
FROM <table name>
[WHERE <condition>];
Example: To display name and marks of 11th class students.

Types of Operators in SQL:

Arithmetic operators:
Arithmetic operator takes two operands and performs a mathematical calculation
on them. However, they can be used only in SELECT command.
The arithmetic operators used in SQL are:

+ Addition
- Subtraction
* Multiplication
/ Division

Consider Table Student-


Example
1. To display new marks of students after giving grace of 5 marks to
each one of them.
Command:

2. To Display the marks of all students after giving 5 grace marks to


them and rename the column as Newmarks.
Command:
Note: The above command is used for viewing purpose only. It will not
make any changes in the original table.
Likewise we can make use of other arithmetic operators also.

Relational operators:
Relational operator is used along with ‘where clause’ to specify criteria. It is used to
compare the two operands.
Types of Relational operators are -
< Less than
<= less than or equal to
> Greater than
>= greater than or equal to
= equal to
! = or <> not equal to

Examples:
Consider Table Student
Admno Firstname DOB mobileno Class Section marks
100 Priyanka 2003-01-13 9811245387 11 A 76.5
123 Suman 2006-04-02 8576230122 6 C NULL
201 Madhav 2002-09-18 9711289701 10 D 69
345 Sambav 2000-08-17 9811456781 12 B 92
134 Madhukar 2007-09-09 9711542908 5 B 71
483 Kavya 2007-06-12 9810211345 5 A 53.5
235 Sanvi 2003-10-11 8657320134 9 D 94

1. Display names and marks of students whose score is greater than 75.

2. Display information of students who are not in class 5.


(We can make use of <> operator also instead of !=)

3. Display names of all students born after 2003-01-01

Logical operators:
Logical operators are used along with 'where clause' to join two or more conditions.
Logical operators are:

➢ AND-In case of ‘AND’ operator the record will be shown in the output only
when all the conditions joined by ‘AND’ evaluates to true.
➢ OR- In case of ‘OR’ operator, the record will be displayed in the output in
case any one condition joined by ‘OR’ evaluates to true.
➢ NOT-NOT operator is used to negate the condition.

Examples:

1. Display information of class 11th students who have scored less than 80
marks.

2. Display the information of students belonging to classes 11th and 12th.

Note:
If we use ‘And’ operator instead of ‘Or’ we will get an empty set
because at one point of time student would be either in 11th or 12th.
We cannot use ‘And’ to join conditions based on same column.
3. Display name, class and section of all students who are not in section A.

LIKE OPERATOR

LIKE OPERATOR is used for pattern searching. This operator is used along with
wildcard characters.
MYSQL has two wild card characters:
➢ Percentage sign (%) – can be replaced by any number of characters (even
zero character).It can be any character from (a-z/A-Z) or number from (0-
9).
➢ Underscore ( _ ) – can be replaced by any single character or number.
Note:
In MySQL, Patterns are case-insensitive by default.
We do not use = or <> while performing pattern searching.

Example:

1. To Display the information of students whose name starts with alphabet


"S".

Here, % replaces one or more characters.

2. To display information about students whose name ends with alphabet ‘i’.

3. To display information of students having ‘a’ at its second position.


4. To display names which are 5 characters long.

In all the above queries,% is replaced by multiple characters whereas _ is replaced


by single character

Range Operators
These operators are used to define range of values in condition.
IN Operator
The IN operator allows us to specify multiple values in a WHERE clause.

Syntax:
SELECT fieldname(s)
FROM table_name
WHERE fieldname IN (value1, value2, ...);
Example:
To display information about students studying in section A and D.

The same output can be obtained using OR operator


Alternative SQL can be:
Note: IN operator is an alternative to multiple OR conditions.

BETWEEN Operator
The BETWEEN operator is used to define the range of values.
Range can include numbers, date or text.
Syntax:
SELECT <fieldname(s)>
FROM <table_name>
WHERE <fieldname> Between <value1> and <value2>;
Note: both value1 and value2 are inclusive.

Example:
1. To display admno and names of students having marks between 40 to 70

Note: In the above Query both 40 and 70 are included in the output.

2. To display name and sections of students belonging to sections A-C.

ORDER BY

This command is used to arrange the records in ascending or descending order.


Ascending order is specified by the keyword ASC. It is the default order.
Descending order is specified by the keyword DESC.
Syntax:

SELECT <column_1>, <column_2>, ... <column_n>


FROM <table_name>
ORDER BY <column> ASC|DESC;

Example:
1. To display the records of students in sorted order of their marks from lowest to
highest.

2. To display the list of students in descending order of their names.

Ordering on multiple fields


3. To display the records in ascending order of their sections and then by name in
descending order.

DISTINCT Clause
The DISTINCT keyword is used to remove duplicate values from a particular
column.
Syntax:
SELECT DISTINCT <column>
FROM <table_name>;
Example:
1. To Display unique classes from student table.
2. Display different sections from student table.

UPDATE Command

This command is used to modify the records in the table.


Syntax:
UPDATE <table_name>
SET <column1 = value1>, <column2 = value2>, ...
[WHERE condition];

Note: Update command make changes in the original table so it should be used
very wisely. If ‘where clause’ is omitted ,it means all the records in the table will be
updated.

Example:
1. To Increase the marks of every student by 5.

Since there is no where clause all records have been updated. Let’s view the table
now to see the changes.

2. To set the marks of Suman as 85.


Let’s view the table again.Marks of Suman has been updated.

ALTER TABLE command


This command is used to modify the structure of the table. Using this DDL
command we can:
✓ add a new column
✓ delete the existing column
✓ modify data type of existing column.

Syntax:
ALTER TABLE <table name>
[ADD/MODIFY/DROP] <column name>;

For example:

1. To Add a new column grade having datatype char


the command will be:

Let’s view the structure of table:

Note: A new column grade has been added in the table student.

2. To Change datatype of grade column from char(1)


to varchar(2) the command will be :
Note : Datatype of grade column has changed.

2. To remove/delete grade column.

Note: column grade has been removed from the table.

DELETE Command
This command is used to remove the records from specified table.
Note: Delete command cannot be used to remove a column or a structure
of table.

Syntax:

DELETE FROM <table name>


[WHERE <condition>];

Example:

1. Remove record of Suman as she has left the school.

Output:
Suman’s record is deleted from the table.
2. Remove the records of students who are born after 2005-01-01.’

Output: Two records deleted from the table.

3. Remove all records.

Output: All records have been deleted.

DROP TABLE (DDL command)


This command is used to remove the entire structure of the table along with
records i.e. using this command both fields and records are removed from the
table.

Syntax:

DROP TABLE<table name>;

For example:
Remove the whole structure of student table.

DROP TABLE student;

Aggregate functions

Aggregate function works on multiple rows and returns a single value. These
functions are also known as group functions. They are used to perform calculations
based upon a particular column.
Syntax:
SELECT aggregate_function(fieldname) from <table_name>;
Some examples of Aggregate functions are:
1. SUM()
2. AVG()
3. MAX()r Science
4. MIN()
5. COUNT()

Consider the table Student

SUM()

This function is used to find the total value of a particular column.

Example:

AVG()

This function is used to find the average value of a particular column.


Example:

MAX()

This function is used to find the maximum/highest value from a particular column.

Example:
MIN()
This function is used to find the minimum/Lowest value from a particular column.
Example:

COUNT()

This function is used to return a count of the non- NULL values in the particular column.

Example:

COUNT(*)

This function is used to find the number of values (i.e. number of rows) in a
particular column. It includes NULL values also.

Example:

Note: Count(*) returns 7 because it counts the NULL value also.

GROUP BY

GROUP BY clause is used to group values from a column, and, if we wish,


perform calculations on that column. We can use COUNT, SUM, AVG functions on
the grouped column.

For example:

Consider the following table-Classes:


1. Display total strength of students in each class.

Since group by clause is used in the above query,we get three classes (6,7,8) in
the output.

Having clause

As mentioned earlier, the 'where' clause is used only to place condition on the
selected columns, whereas the 'HAVING' clause is used to place condition on
groups created by 'group by' clause, because here the 'WHERE' clause is not
useable.

Example:

1. Display the total strength of students in each class having strength less than
150.

In the above output, class 6 is not displayed as its total strength is more then 150.

Points to Remember

➢ DDL: Data Definition Language (DDL) or Data Description Language (DDL).

➢ DML: Data Manipulation Language (DML).

➢ Datatype: type of value that a particular attribute of a table is going to hold.

➢ String data types: CHAR, VARCHAR


➢ Numeric data types: INT, DECIMAL

➢ Date: DATE

➢ String, char and date values are always enclosed within single quotes.

➢ CREATE DATABASE: used to create a new database.

➢ USE DATABASE: Used to open any existing database.

➢ SHOW DATBASES: Displays the list of existing databases.

➢ SHOW TABLES: Displays the list of tables existing in current database.

➢ CREATE TABLE: Used to create structure of the table.

➢ ALTER TABLE: Used to make changes in the structure.

➢ DROP TABLE: To remove full table (records along with structure)

➢ INSERT INTO: To add new records.

➢ SELECT: To display row or column information .

➢ Where: To specify condition

➢ DISTINCT: To select unique information.

➢ ORDER BY: To display the records in either ascending or descending order.


Default ordering is ascending

➢ MAX():To select maximum value of a particular column.

➢ MIN():To select minimum value of a particular column.

➢ SUM():To find total value of a particular column.

➢ AVG():To find average value of a particular column.

➢ COUNT(): Number of records in the table excluding NULL.

➢ COUNT(*):Number of records including NULL.

You might also like