MY SQL Notes
MY SQL Notes
Creating a Database.
The following command will create School database in MySQL.
mysql> CREATE DATABASE School;
Opening a database
To open an existing database, following command is used.
mysql> USE school ;
Getting listings of database and tables
mysql> SHOW DATABASES;
mysql> SHOW TABLES;
Deleting a Database and Table
mysql> DROP DATABASE School;
mysql> DROP TABLE Student;
Viewing Table Structure
Select database();
mysql> DESCRIBE Student; Shows the name of
currently open database
Creating Tables & Inserting records
Creating Simple Tables:
CREATE TABLE < Table Name>
(<Col name1><data type>[(size)],….);
Data types- INTEGER, NUMERIC(P,D), CHAR(n), VARCHAR(n), DATE etc.
mysql> CREATE TABLE Employee
(empID integer, Employee
ename char(30),
empID ename city pay
city char(25),
pay decimal(10,2));
Inserting Records:
INSERT INTO <Table Name> VALUES (value1, vale2, …...);
String and Date type values must be enclosed in single or double quotes.
mysql> INSERT INTO Employee VALUES (1,‘Amitabh’,‘Allahabad’,15000);
mysql> INSERT INTO Employee VALUES (2, ‘Akbar’, ‘Dehradun’,20000);
mysql> INSERT INTO Employee VALUES (3, ‘Anthony’, ‘Mumbai’,10500);
Making Simple Queries Using SELECT
The SELECT command of SQL, empower you to make a
request (queries) to retrieve stored records from the
database.
The syntax of SQL is given below-
SELECT < [Distinct | ALL] *| column name(s)>
FROM <table(s)>
WHERE <condition>
ORDER BY <column name> [ASC | DESC] ;
Consider the table Student having some records as –
MySQL will display the all records with all columns in the Student table.
* Is used to represent all columns.
WHERE <Condition>
We can select specific records by specifying conditions with
WHERE clause.
mysql> SELECT * FROM Student WHERE City=‘Mumbai’;
StID Name Fname DOB City Class
S4 Salman Salim Javed 1972-04-10 Mumbai 10
S5 Abhishek Amitabh 1975-03-12 Mumbai 10
Relational Operators
We can use the following Relational operators in condition.
=, > , < , >=, <=, <>, IS , LIKE, IN, BETWEEN
Logical Operators
We can use the following Logical Operators to connect two conditions.
OR , AND , NOT (!)
Constraints Description
NOT NULL Ensures that a column cannot have NULL value.
PRIMARY KEY Used to identify a row uniquely.
DEFAULT* Provides a default value for a column, if no value is given.
UNIQUE* Ensures that all values in a column are different.
CHECK* Ensures that value for a column should satisfy certain
condition.
FOREIGN KEY* Used to ensure Referential Integrity of the data.
UNIQUE UNIQUE allows NULL values but PRIMERY KEY does not.
v/s A table may have multiple UNIQUE constraints, but there
PRIMARY KEY must be only one PRIMERY KEY constraints in a table.
Implementing Primary Key Constraints