Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

SQL 1

Uploaded by

beauty within us
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

SQL 1

Uploaded by

beauty within us
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Information Management

System Lab

CBCA109
Continuous Lab Evaluation
About
(30)
IMS Lab
Evaluation
Data and Information

Data is raw, unorganized facts •Data can be something simple, •When data is processed,
that need to be processed. random and useless until it is organized, structured or
organized. presented in a given context to
make it useful, it is called
information.
–Each student's exam marks –The average score of a department or of
the entire college is information
that is derived from the given data.
Information Management System

• An Information Management System


consists of
– A collection of interrelated and
persistent data (usually referred as
database).
– A set of application programs used to
access, update and manage that data
(usually referred as management
system).
Query Language

SQL (structured query


language) is a computer MySQL is one of the most
language aimed to store, popular open source SQL
manipulate, and retrieve database management
data stored in relational system.
databases.

It is developed, distributed
Supports including Windows,
and supported by Oracle
Linux, UNIX, Mac…
corporation.
Install • Scroll down this page
MySQL
Install MySQL • Click on MySQL Community downloads
Install
MySQL
• Click on the option according to your
environment
Install
MySQL
• For windows, download
from the 1st option
MySQL
Installer
• Choose Developer
and click next and
continue the process
MySQL
Installer
• click next and
continue the process
SQL categorization
SQL commands are mainly categorized into
four categories as:
• DDL – Data Definition Language
• DML – Data Manipulation Language
• DQL – Data Query Language
• DCL – Data Control Language
DDL(Data Definition
TRUNCATE–is used to
Language) : Data Definition
remove all records from a
Language consists of the SQL ALTER-is used to alter the
table, including all spaces
commands that can be used structure of the database.
allocated for the records are
to define the database
removed.
schema.
DDL
It simply deals with
descriptions of the database
COMMENT –is used to add
schema and is used to create DROP – is used to delete
comments to the data
and modify the structure of objects from the database.
dictionary.
database objects in the
database.

CREATE – is used to create


the database or its objects RENAME –is used to rename
Some examples of DDL
(like table, index, function, an object existing in the
commands:
views, store procedure and database.
triggers).
DML
DML(Data Manipulation Language) : The SQL commands that deals with the
manipulation of data present in the database belong to Data Manipulation Language.

Examples of DML:

INSERT– is used to insert data into a table.

UPDATE– is used to update existing data within a table.

DELETE – is used to delete records from a database table.


DQL

DQL (Data Query The purpose of DQL Example of DQL: SELECT– is used to retrieve
Language) : Command is to get some data from the a database.
schema relation based on
the query.
DCL

DCL(Data Control Language) : DCL includes Examples of DCL commands:


commands such as GRANT and REVOKE which
mainly deals with the rights, permissions and
other controls of the database system.
GRANT-gives user’s access privileges to database.
REVOKE-withdraw user’s access privileges given by using the
GRANT command.
TCL commands are basically used for
managing and controlling the
transactions in a database to
maintain consistency. And it also
helps a user manage all the changes
made by the DML commands for
maintaining its transactions.
TCL
TCL(transaction Control Language) : TCL commands deals with the transaction within
the database.

Examples of TCL commands:

COMMIT– commits a Transaction.

ROLLBACK– rollbacks a transaction in case of any error occurs.

SAVEPOINT–sets a savepoint within a transaction.

SET TRANSACTION–specify characteristics for the transaction.


• The CREATE DATABASE
statement is used to create a new
SQL database.
Syntax
• CREATE DATABASE databasena
me;
Create
Example:
Database • CREATE DATABASE testDB;
To check whether the database is
present, use following SQL command
• SHOW DATABASES;
Drop Database
• The DROP DATABASE statement is used to drop
an existing SQL database.

Syntax
• DROP DATABASE databasename;
Note: Deleting a database will result in loss of complete
information stored in the database!
Example
• DROP DATABASE testDB;
Tip: You can check it in the list of databases with the
following SQL command: SHOW DATABASES;
Use Database
To use the database, we need to write following SQL
command:
Syntax
• USE databasename;
Example
• USE testDB;
Creating Table
• The CREATE TABLE statement is used to create a new table in
a database.

Syntax
• CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);

• The column parameters specify the names of the columns of the


table.

• The datatype parameter specifies the type of data the column


can hold (e.g. varchar, integer, date, etc.).
Create Table example
SQL CREATE TABLE Example

• The following example creates a table


called "Persons" that contains five
columns: PersonID, LastName,
FirstName, Address, and City:

Example
• CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
Popular Data Types

Data Type Syntax Explanation


CHAR(size) Maximum size of 255 characters.
size is the number of characters to store.
VARCHAR(size) Maximum size of 255 characters.
Variable-length string.
TEXT(size) Maximum size of 65,535 characters.
Where size is the number of characters to store.
BINARY(size) Maximum size of 255 characters.
Where size is the number of binary characters to store. Fixed-length strings.
INT(m) Standard integer value.
Signed values range from -2147483648 to 2147483647. Unsigned values range from 0 to
4294967295.
FLOAT(m,d) Single precision floating point number.
Where m is the total digits and d is the number of digits after the decimal.
DOUBLE(m,d) Double precision floating point number.
Where m is the total digits and d is the number of digits after the decimal.
DATE Values range from '1000-01-01' to '9999-12-31'.
Displayed as 'YYYY-MM-DD'.
DATETIME Values range from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.
Displayed as 'YYYY-MM-DD HH:MM:SS'.
Drop Table
The DROP TABLE statement is used to drop an existing table in a database.

Syntax

DROP TABLE table_name;

Note: Deleting a table will result in loss of complete information stored in


the table!
Example:

DROP TABLE team;


Truncate Table
• The TRUNCATE TABLE statement is used
to delete the data inside a table, but not
the table itself.

Syntax
• TRUNCATE TABLE table_name;
Example
• TRUNCATE TABLE team;
Alter Table
• The ALTER TABLE statement is used to add,
delete, or modify columns in an existing table.

• The ALTER TABLE statement is also used to add


and drop various constraints on an existing table.
ALTER Table - ADD
Column
To add a column in a table, use the following syntax:

• ALTER TABLE table_name


ADD column_name datatype;

The following SQL adds an "Email" column to the


“Persons" table:

Example
• ALTER TABLE Persons
ADD Email varchar(255);
ALTER Table -
DROP Column
To delete a column in a table, use the following
syntax (notice that some database systems don't allow
deleting a column):

• ALTER TABLE table_name


DROP COLUMN column_name;

• The following SQL deletes the "Email" column


from the “Persons" table:

Example
• ALTER TABLE Persons
DROP COLUMN Email;
ALTER Table - ALTER/MODIFY
Column
To change the data type of a column in a table, use the
following syntax:
ALTER TABLE table_name
MODIFY COLUMN column_name datatype;
Example

ALTER TABLE Persons


ADD DateOfBirth date;
ALTER TABLE Persons
MODIFY COLUMN DateOfBirth year;
RENAME Table
• RENAME TABLE renames one or more tables. You
must have ALTER and DROP privileges for the
original table, and CREATE and INSERT privileges
for the new table.
Syntax:
• RENAME TABLE tbname TO new_tbname [,
tbname2 TO new_tbname2] … ;
Example:
To rename a table named Persons to Employee, use this
statement:
• RENAME TABLE Persons TO Employee;
We can also use
• ALTER TABLE Persons RENAME Employee;
RENAME Contd.
• RENAME TABLE, unlike ALTER TABLE, can
rename multiple tables within a single statement:
• RENAME TABLE old_table1 TO new_table1,
old_table2 TO new_table2,
old_table3 TO new_table3;
• Renaming operations are performed left to right.
Thus, to swap two table names, do this (assuming
that a table with the intermediary
name tmp_table does not already exist):
• RENAME TABLE old_table TO tmp_table,
new_table TO old_table,
tmp_table TO new_table;
Add Comment

Add comment corresponding to a colum


• ALTER TABLE Example
MODIFY COLUMN `id`int(10) COMMENT 'Look, I am a comment!’;
SELECT
Command

The SELECT statement The data returned is Syntax


is used to select data stored in a result table,
from a database. called the result-set.

SELECT column1, colum Here, column1, SELECT * FROM table_n


n2, ... column2, ... are the ame
FROM table_name; field names of the table
you want to select data
from. If you want to
select all the fields
available in the table,
use the following
syntax:
SELECT DISTINCT
Command
• The SELECT DISTINCT statement is used to return
only distinct (different) values.

• Inside a table, a column often contains many


duplicate values; and sometimes you only want to
list the different (distinct) values.

Syntax

• SELECT DISTINCT column1, column2, ...


FROM table_name;

Example

• SELECT DISTINCT City FROM Persons;


WHERE Clause

The WHERE clause is used to filter records.

The WHERE clause is used to extract only those records


that fulfill a specified condition.

Syntax

• SELECT column1, column2, ...


FROM table_name
WHERE condition;

Example

• SELECT * FROM Persons


WHERE City=‘Delhi’;
MySQL Constraints

NOT NULL: By default, a column can hold NULL values. The NOT
NULL constraint enforces a column to NOT accept NULL values.
•Eg. Select position, pname, role from team where shirt_no is NOT NULL.

UNIQUE: Ensures that all the values in columns are unique. (Eg.
Roll no, Date of Birth, tshirt no of same team players etc.)

PRIMARY KEY: Combination of NOT NULL and UNIQUE.

FOREIGN KEY: Uniquely identify a row/record in any other


database table.

CHECK: The check constraints ensures that all values in a column


specify certain condition.
Example: Create
Table
create table team(
position varchar(10),
pname varchar(30),
role varchar(20));
insert into team

values ('P1','V. Kohli','Bat'),

('P2','R. Sharma','Bat' ),
Insert into
Table ('P3','M.Dhoni','Wicket'),

('P4','J.Bumrah','Ball'),

('P5','K.Yadav','Ball');
How to display

• SELECT position,
pname from team;
• select * from team;
Delete a Member

delete from team


where position='P5';

select * from team;

Delete from team; //all


the records will be deleted
Update

update team
set pname='B.Kumar'
where position='P4';

select * from team;


Alter Table Alter table team
add (shirt_no INT);
update team
set shirt_no=18 where
position='P1';

select * from team;


Use Case 1 (Shopping
Record)
Customers Table
CREATE TABLE customers (
customerNumber varchar(11) NOT NULL,
customerName varchar(50) NOT NULL,
contactLastName varchar(50) NOT NULL,
contactFirstName varchar(50) NOT NULL,
phone varchar(50) NOT NULL,
addressLine1 varchar(50) NOT NULL,
addressLine2 varchar(50) DEFAULT NULL,
city varchar(50) NOT NULL,
state varchar(50) DEFAULT NULL,
postalCode varchar(15) DEFAULT NULL,
country varchar(50) NOT NULL,
salesRepEmployeeNumber int(11) DEFAULT NULL,
creditLimit decimal(10,2) DEFAULT NULL,
PRIMARY KEY (customerNumber)) ;
Employees Table
CREATE TABLE employees (
employeeNumber int(11) NOT NULL,
lastName varchar(50) NOT NULL,
firstName varchar(50) NOT NULL,
extension varchar(10) NOT NULL,
email varchar(100) NOT NULL,
officeCode varchar(10) NOT NULL,
reportsTo int(11) DEFAULT NULL,
jobTitle varchar(50) NOT NULL,
PRIMARY KEY (employeeNumber));
Order Details Table
CREATE TABLE orderdetails (
orderNumber int(11) NOT NULL,
productCode varchar(15) NOT NULL,
quantityOrdered int(11) NOT NULL,
priceEach decimal(10,2) NOT NULL,
orderLineNumber smallint(6) NOT NULL,
PRIMARY KEY (orderNumber,productCode)) ;

Other tables can be created in the similar


process.
Use Case
2: Office
Record
Employee Table
CREATE TABLE employees (
emp_no INT NOT NULL,
birth_date DATE NOT NULL,
first_name VARCHAR(14) NOT NULL,
last_name VARCHAR(16) NOT NULL,
gender ENUM ('M','F') NOT NULL,
hire_date DATE NOT NULL,
PRIMARY KEY (emp_no)
);
Department Table
CREATE TABLE departments (

dept_no CHAR(4) NOT NULL,

dept_name VARCHAR(40) NOT NULL,

PRIMARY KEY (dept_no),

UNIQUE KEY (dept_name)

);
Other tables can be created in the similar process.
Assignment
Create following two tables:
1) Find out the
Branch_name
Branch_name Loan_number amount where amount
>=2000.
Downtown L-170 3000
2) Find out the
Redwood L-230 4000 name of the
Perryridge L-260 1700 customer whose
loan_number is L-
170.
3) Delete the
Customer_name Loan_number customer whose
Jones L-170 loan_number is
155.
Smith L-230 4) Add gender
Hayes L-155 column in the
second table.
THANKYOU

You might also like