SQL Notes
~~~~~~~~~~~~~~~~~
Suraj T -
Mobile : 7603893398
E-mail : [email protected]
-----------------------------------------------------------------------------------
---
Data
~~~~~~~~~~~
Collection of information
Database
~~~~~~~~~~~~~
Collection of related information stored at one place.
Table
~~~~~~
Table consists of rows and columns
Rows
~~~~~~~~
Horizontal ones
Columns
~~~~~~~~~~
Vertical ones
1 Row = 1 Record
Each data is stored in 1 Record
DBMS
~~~~~~~~~~~
Database Management System
Application or Software used to store and manage database.
Examples of DBMS
~~~~~~~~~~~~~~~~~~
1. MySQL Open Source Oracle (Sun Microsystems)
2. SQL Server Microsoft
3. Oracle Oracle
4. PostgresSQL Open Source
CRUD Operations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C Create CREATE
R Read SELECT
U Update UPDATE
D Delete DELETE / DROP
Features of DBMS
~~~~~~~~~~~~~~~~~
-- Interface between Database and User
-- Software to store , retrieve, define and manage data in the database.
-- Easy CRUD Operations.
-- Takes care of authentication(security), authorization, concurrency, logging,
backup, optimization etc.
-- should support connection using other applications and other programming
languages.
RDBMS
~~~~~~~~~~~~~
Relational Database Management Systems
Examples of RDBMS
~~~~~~~~~~~~~~~~~~
1. MySQL Open Source Oracle (Sun Microsystems)
2. SQL Server Microsoft
3. Oracle Oracle
4. PostgresSQL Open Source
Datatypes in MySQL
~~~~~~~~~~~~~~~~~~~~~
20 number
"twenty" string
'twenty' string
String
~~~~~~~~~
set of characters
125 ASCII Characters
either double quotes ""
or single quotes ''
Examples:
~~~~~~~~~~
"abcd!@#$"
'sql'
"mysql"
"20"
Datatypes for String
~~~~~~~~~~~~~~~~~~~~~~~~
-----------------------------------------------------------------------------------
------------------------------------------------------------
Datatype Maximum number of bytes
-----------------------------------------------------------------------------------
--------------------------------------------------------------
CHAR(10) Max 255 bytes
VARCHAR(10) Max 65, 535 bytes
-----------------------------------------------------------------------------------
---------------------------------------------------------------------
Example
CHAR(10) JOHN => 10 bytes
VARCHAR(10) JOHN => 4 bytes
CHAR When the size of charcaters is fixed
VARCHAR When the size of characters is unknown
Text
~~~~~
-----------------------------------------------------------------------------------
--------------------------------------------------------------
Text Type Maximum number of bytes
-----------------------------------------------------------------------------------
----------------------------------------------------------------
TINYTEXT 255
TEXT 65,535
MEDIUMTEXT 16,777,215
LONGTEXT 4,294,967,295
-----------------------------------------------------------------------------------
-----------------------------------------------------------------
Datatype for storing files
BLOB Binary Large Object File
BLOB Type
~~~~~~~~~~~~~
TINYBLOB
BLOB
MEDIUMBLOB
LONGBLOB
-----------------------------------------------------------------------------------
-------------------------------------------
Numbers / Numericals
~~~~~~~~~~~~~~~~~~~~~~~
1. Whole Number 1, -1
2. Decimal Number 1.0, -1.0
Whole Number
~~~~~~~~~~~~~~~~
-----------------------------------------------------------------------------------
-------------------------------------------------------------
Whole Number Type Signed Range
-----------------------------------------------------------------------------------
----------------------------------------------------------------
TINYINT -128 to 127
SMALLINT -32,768 to 32,767
MEDIUMINT -8,388,608 to 8,388,607
INT -2,147,483,648 to 2,147,483,647
BIGINT -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
-----------------------------------------------------------------------------------
----------------------------------------------------------------
specifying size of digits for INT datatype is optional INT(10) OR INT
Decimal Number
~~~~~~~~~~~~~~~~~
DECIMAL(TOTAL_DIGITS, TOTAL_DECIMAL_DIGIT)
Example
~~~~~~~~~~~~~~~~~
123.4 => DECIMAL(4, 1)
123.45 => DECIMAL(5, 2)
12345.6789 => DECIMAL(9, 4)
123456789.0 => DECIMAL(9, 0)
12345.10 => DECIMAL(7, 2)
Date
~~~~~~~~~
-----------------------------------------------------------------------------------
----------------------------------------------------
Date Datatype Default Format Allowable Values
-----------------------------------------------------------------------------------
----------------------------------------------------
DATE YYYY-MM-DD 1000-01-01 to 9999-12-31
DATETIME YYYY-MM-DD HH:MI:SS 1000-01-01 00:00:00 to 9999-12-31 23:59:59
TIMESTAMP YYYY-MM-DD HH:MI:SS 1970-01-01 00:00:00 to 2037-12-31 23:59:59
YEAR YYYY 1901 to 2155
TIME HHH:MI:SS -838:59:59 to 838:59:59
-----------------------------------------------------------------------------------
---------------------------------------------------
Example
~~~~~~~~~~~~~
DATETIME Custom Date and Time / User Specified Date and Time
e.g. Date of Birth, Train Time, Bus Time
TIMESTAMP System Date and Time
e.g. Login Time, Logout Time, Start time, End Time, Check In / Check Out, Ticket
Booking Time
To store duration we will use TIME datatype
SQL - Structured Query Language - Sequel
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Classification of SQL Statement / SQL Commands
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
DDL - Data Definition Language
DML - Data Manipulation Language
DCL - Data Control Language
TCL - Transaction Control Language
DRL / DQL - Data Retrivel Language / Data Query Language
-----------------------------------------------------------------------------------
-------------------------------
DDL - Data Definition Language
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CREATE
ALTER
DROP
RENAME
ADD
MODIFY
TRUNCATE
-- comments in mysql
-- two hyphen symbols then space then comments
-- show all the databases in mysql server
SHOW DATABASES;
-- create a database monkey
CREATE DATABASE monkey;
SHOW DATABASES;
-- delete database monkey in mysql server
DROP DATABASE monkey;
SHOW DATABASES;
CREATE DATABASE monkey;
-- it will show error as database already present
CREATE DATABASE monkey;
-- it will not show error if database is already present
CREATE DATABASE IF NOT EXISTS monkey;
DROP DATABASE monkey;
-- it will show error as database does not exist
DROP DATABASE monkey;
-- it will not error if database does not exist
DROP DATABASE IF EXISTS monkey;
CREATE DATABASE IF NOT EXISTS monkey;
SHOW DATABASES;
USE monkey;
-- create a new table student
CREATE TABLE student (
name VARCHAR(50)
);
SHOW TABLES;
-- to show the structure of the table
DESCRIBE student;
DESC student;
-- to delete table
DROP TABLE student;
SHOW TABLES;
-- it will not throw error if the table is not available. it will show only warning
DROP TABLE IF EXISTS student;
PRIMARY KEY === UNIQUE + NOT NULL
-- add primary key to column in table
-- adding primary key at the last after declaring all the coumns
CREATE TABLE student (
id INT,
name VARCHAR(50),
PRIMARY KEY(id)
);
DESCRIBE student;
DROP TABLE student;
-- adding primary key directly to the column in table
CREATE TABLE student (
id INT PRIMARY KEY,
name VARCHAR(50)
);
DESCRIBE student;
DROP TABLE student;
-- add NOT NULL condition to column
CREATE TABLE student (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
DESCRIBE student;
DROP TABLE student;
-- add DEFAULT condition to column
CREATE TABLE student(
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
city VARCHAR(50) DEFAULT 'bangalore'
);
DESCRIBE student;
DROP TABLE student;
-- add UNIQUE condition to column
CREATE TABLE student(
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
city VARCHAR(50) DEFAULT "bangalore",
aadhaar BIGINT UNIQUE
);
DESCRIBE student;
DROP TABLE student;
NOT NULL + UNIQUE === PRIMARY KEY
-- column having NOT NULL and UNIQUE will automatically become PRIMARY KEY
CREATE TABLE student (
name VARCHAR(50) NOT NULL,
city VARCHAR(50) DEFAULT "bangalore",
aadhaar BIGINT NOT NULL UNIQUE
);
DESCRIBE student;
DROP TABLE student;
-- table will have only one primary key
CREATE TABLE student (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
city VARCHAR(50) DEFAULT 'bangalore',
aadhaar BIGINT NOT NULL UNIQUE
);
DESCRIBE student;
DROP TABLE student;
-----------------------------------------------------------------------------------
-------------------------------------------------
-- TASK 1
-- create customer table
+---------------+-----------------+----------+----------+-------------+---------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-----------------+----------+----------+-------------+---------+
| id | int | NO | PRI | NULL |
|
| name | varchar(50) | NO | | NULL | |
| mobile | int | YES | UNI | NULL |
|
| gender | char(1) | YES | | M |
|
+--------------+------------------+---------+----------+--------------+--------+
-- create customer table
CREATE TABLE customer (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
mobile INT UNIQUE,
gender CHAR(1) DEFAULT "M"
);
DESCRIBE customer;
DROP TABLE customer;
-----------------------------------------------------------------------------------
-------------------------------------------
-- TASK 2
-- create person table
+-------------+------------------+-------+-------+---------------+---------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------------+-------+-------+---------------+---------+
| id | int | NO | PRI | NULL | |
| name | varchar(50) | NO | | NULL | |
| aadhaar | bigint | YES | UNI | NULL | |
| city | varchar(50) | YES | | mysore | |
| state | varchar(50) | YES | | karnataka | |
| country | varchar(50) | YES | | india | |
+------------+------------------+--------+-------+----------------+-------+
-- by default AUTO_INCREMENT starts at 1
-- to change the starting number of AUTO_INCREMENT
ALTER TABLE student
AUTO_INCREMENT = 101;
DROP TABLE student;
-- add CHECK condition to column
CREATE TABLE student(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
city VARCHAR(50) DEFAULT "bangalore",
aadhaar INT UNIQUE,
age INT CHECK(age > 17)
);
DESCRIBE student;
DROP TABLE student;
-----------------------------------------------------------------------------------
------------------------------------------------------
-- ALTER -- RENAME
-- add new column
-- change column datatype
-- change column name
-- delete column
-- change table name
SHOW TABLES;
CREATE TABLE student(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
city VARCHAR(50) DEFAULT "bangalore",
aadhaar INT UNIQUE,
age INT CHECK(age > 17)
);
DESCRIBE student;
-- add new column
ALTER TABLE student
ADD COLUMN state VARCHAR(50);
DESCRIBE student;
-- change column datatype
ALTER TABLE student
MODIFY COLUMN state CHAR(50);
DESCRIBE student;
-- change column name
ALTER TABLE student
RENAME COLUMN state TO student_state;
DESCRIBE student;
-- delete column
ALTER TABLE student
DROP COLUMN student_state;
DESCRIBE student;
-- change table name
RENAME TABLE student TO stu;
SHOW TABLES;
RENAME TABLE stu TO student;
SHOW TABLES;
-----------------------------------------------------------------------------------
-----------------------------------------------
-- TRUNCATE
~~~~~~~~~~~~~~~~
-- Only the data or all the records will be deleted and Table structure will not be
deleted
TRUNCATE TABLE student;
TRUNCATE student;
SHOW TABLES;
DESCRIBE student;
-----------------------------------------------------------------------------------
-----------------------------------------------------------
-- DML - Data Manipulation Language
-- INSERT
-- UPDATE
-- DELETE
-----------------------------------------------------------------------------------
-----------------------------------------------------
-- INSERT
~~~~~~~~~~~~~
INSERT INTO student
(name, age)
VALUES
("surya", 40);
-- to show all the columns / fields from the table
SELECT *
FROM student;
-- when inserting data without specifying column names
-- 1. enter data for all the fields. Value count should match with column count.
-- 2. chances of data getting inserted in wrong columns.
-- 3. insert data in the same order of columns in table.
-- inserting without specifying column names
INSERT INTO student
VALUES
(2, "dhanush", "mysore", 123456, 50);
SELECT *
FROM student;
-- chances of data getting inserted in wrong columns
INSERT INTO student
VALUES
(3, "mumbai", "shreyas", 987654, 29);
SELECT *
FROM student;
INSERT INTO student
(city, age, name)
VALUES
("mandya", 23, "dharshan");
SELECT *
FROM student;
-- inserting multiple set of values
INSERT INTO student
(name, city, age)
VALUES
("preetam", "hassan", 24),
("ramya", "chennai", 30),
("divya", "malur", 21),
("rajnikanth", "mangalore", 18)
;
SELECT *
FROM student;
-- it will throw error as check constraint is violated
INSERT INTO student
(name, city, age)
VALUES
("katappa", "dholakpur", 17);
-- to show specific column from the table
SELECT name, city
FROM student;
-- ORDER BY
-- Default is ascending
-- ASC ascending
-- DESC descending
-- Ascending Order
SELECT *
FROM student
ORDER BY name;
-- Descending Order
SELECT *
FROM student
ORDER BY name DESC;
SELECT city, name, age
FROM student
ORDER BY city;
SELECT city, name, age
FROM student
ORDER BY city, name DESC;
DROP TABLE student;
-- Constraints in MYSQL
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- NOT NULL
-- AUTO_INCREMENT
-- UNIQUE
-- DEFAULT
-- CHECK
-- PRIMARY KEY
-- FOREIGN KEY
----------------------------------------------------------------
-- give name "lion" for CHECK CONSTRAINT
CREATE TABLE student (
id INT PRIMARY KEy AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
city VARCHAR(50) DEFAULT "bangalore",
salary INT,
CONSTRAINT lion CHECK(salary > 10000)
);
DESCRIBE student;
INSERT INTO student
(name, city, salary) VALUES
("kiran", "bangalore", 15000),
("smruti", "kumta", 20000),
("aparna", "kolar", 25000),
("srivathsa", "kanakapura", 30000),
("pruthvi", "shimoga", 35000),
("naveed", "shimoga", 40000),
("sachin", "shimoga", 45000),
("tanush", "hosadurga", 50000),
("pavan sai", "bagepalli", 55000),
("nishan", "mysore", 60000),
("kaushik", "udupi", 65000),
("srinivas", "bangalore", 70000),
("rahul choudhary", "bangalore", 75000),
("dhanush", "tumkur", 80000),
("swamy b. c.", "channagiri", 85000),
("manjunath b. h.", "shimoga", 90000),
("chandan", "hubli", 95000),
("narendara", "channagiri", 100000),
("narasimhulu", "anantapur", 105000),
("aditya", "mangalore", 110000),
("nuthan gowda", "tumkur", 115000),
("dayasagar", "davangere", 120000),
("amar", "bidar", 125000),
("ajay", "gulbarga", 130000),
("prajwal", "mysore", 135000),
("srinath r", "chikkaballapur", 45000)
;
SELECT *
FROM student
ORDER BY name, city;
-- clauses
-- WHERE clause
-- filter the rows
Mathematical Operators
~~~~~~~~~~~~~~~~~~~~~~~~~
< Less Than
> Greater Than
<= Less Than Or Equal To
>= Greater Than Or Equal To
= Equal To
<> Not Equal To
!= Not Equal To
Logical Operators
~~~~~~~~~~~~~~~~~~~~~
AND Logical And Operator
OR Logical Or Operator
NOT Logical Not Operator
BETWEEN Between certain range of numbers
IN Multiple possible values for a column
LIKE Search for a pattern
-- less than operator
SELECT *
FROM student
WHERE salary < 50000;
-- greater than operator
SELECT *
FROM student
WHERE salary > 50000;
-- equal to operator
SELECT *
FROM student
WHERE salary = 50000;
SELECT *
FROM student
WHERE city = "shimoga";
-- less than or equal to operator
SELECT *
FROM student
WHERE salary <= 50000;
-- greater than or equal to operator
SELECT *
FROM student
WHERE salary >= 50000;
-- not equal to operator
SELECT *
FROM student
WHERE salary <> 50000
ORDER BY salary;
-- not equal to operator
SELECT *
FROM student
WHERE salary != 50000
ORDER BY salary;
-- IN
-- search for students from bangalore and mysore
SELECT *
FROM student
WHERE city IN ("bangalore", "mysore")
ORDER BY city, name;
-- Logical Operator NOT
-- NOT
-- NOT(TRUE) === FALSE
-- NOT(FALSE) === TRUE
-- NOT IN
-- search for students who are not from bangalore and mysore
SELECT *
FROM student
WHERE city NOT IN ("bangalore", "mysore")
ORDER BY city, name;
-- NOT
SELECT NOT 0;
SELECT NOT 1;
-- output => NULL
SELECT NOT (NOT NULL);
-- output => NULL
SELECT NOT NULL;
-- alias using AS keyword
-- AS
SELECT NOT (NOT NULL) AS output;
SELECT NOT (NOT NULL) AS "output";
SELECT NOT (NOT NULL) AS "sun shine";
SELECT NOT (NOT NULL) AS sun_shine;
TASK
-- show all the students who are not from bangalore using NOT keyword and without
using IN keyword
SELECT *
FROM student
WHERE NOT city = "bangalore";
-- alias using AS keyword
SELECT name AS "student name"
FROM student;
-- alias without using AS keyword
SELECT name "student name"
FROM student;
-- Logical Operator AND
-- left and right conditions should be from different columns and not from same
columns
-- left condition AND right condition
-- true AND true => output
-- true AND false => empty set
-- false AND true => empty set
-- false AND false => empty set
-- output will come
SELECT *
FROM student
WHERE name = "naveed" AND city = "shimoga";
-- empty set
SELECT *
FROM student
WHERE city = "bangalore" AND city = "mysore";
-- empty set
SELECT *
FROM student
WHERE name = "naveed" AND city = "bangalore";
-- Logigal Operator OR
-- left condition OR right condition
-- true OR true => output
-- true OR false => output
-- false OR true => output
-- false OR false => empty set
-- output will come