0% found this document useful (0 votes)
19 views11 pages

IP MySQL SQL NOTES

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
19 views11 pages

IP MySQL SQL NOTES

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 11

INTRODUCTION TO MySQL

1. What is MySQL? MySQL is a free, open-source Relational Database Management System (RDBMS)
that uses Structured Query Language (SQL). In MySQL database, information is stored in the form of
Tables.
Some of the key features of MySQL are:
• Speed: MySQL runs very fast
• Ease of Use: MySQL is a simple database system and gives a high performance.
• Cost: MySQL is available free of cost.
• Query Language Support: MySQL supports standards-based SQL.
• Security: MySQL offers password systems that keeps the database secure.

2. What is the use SQL in MySQL?


Structured Query Language (SQL) is a language that is used to access data within the MySQL
database. It is a language that enables us to create and operate on relational databases.SQL is a set of
commands that is recognized by nearly all RDBMSs.

3. Differentiate between DDL, DML and TCL commands.


Data Definition Language (DDL) Commands: These SQL commands allow to perform task
related to data definition. Through these commands we can perform tasks like CREATE, ALTER
and DROP database objects,

Data Manipulation Language (DML) Commands: These SQL commands are used to manipulate
data. For example, UPDATE, INSERT INTO, SELECT etc. are DML commands.

Transaction Control Commands: These SQL commands are used to manage and control the
transactions. Some examples of TCL command are COMMIT, ROLLBACK, and SAVEPOINT etc.

4. What are the various data types used in SQL?


Data types of SQL
a) Numeric Data Type
• INT/INTEGER
• FLOAT (M, D)
• DOUBLE (M, D)
• DECIMAL (M, D)
b) String Data Type
• CHAR(N)
• VARCHAR(N)
c) Date and Time
• Date
• Time
FLOAT (M, D)
You can define the display length (M) and the number of decimals(D). This is not required and will default to
(10,2), where 2 is the number of decimals and 10 is the total number of digits(including decimals). Decimal
precision go to 24 places for FLOAT

DOUBLE (M, D)
You can define the display length (M) and the number of decimals(D). This is not required and will default to
(16,4), where 4 is the number of decimals and 10 is the total number of digits (including decimals). Decimal
precision go to 53 places for DOUBLE.

DECIMAL (M, D)
Defining the display length (M) and the number of decimals(D) is required.

5. What is the difference between CHAR(n) and VARCHAR(n)?


CHAR(n) is fixed length string data type, in which padding is done with blank space to keep the length
fixed.
VARCHAR(n) is variable length string data type where no padding is done.

6. SQL COMMANDS

Database Commands in MySql


Getting listings of available databases
mysql> SHOW DATABASES;

Creating a database in
mysql> CREATE database myschool;

Deleting a database mysql


mysql > DROP database <databasename>;

to remove table mysql


mysql > drop table <tablename>;

After database creation we can open the existing 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;
• CREATE TABLE command:
Create table command is used to create a table in SQL. It is a DDL type of command. The general syntax
of creating a table is:
create table <table> (
<column 1> <data type> [not null] [unique] [<column constraint>],
.........
<column n> <data type> [not null] [unique] [<column constraint>],
[<table constraint(s)>]
);

Example:
CREATE TABLE student (
Roll_no integer not null primary key,
Name varchar(25) not null,
Class varchar(10),
Marks integer check(marks>0),
City varchar(25) );
7. Define various SQL constraints.
Constraints:
Constraints are the conditions that can be enforced on the attributes of a relation. The constraints come
in play whenever we try to insert, delete or update a record in a relation.
• NOT NULL
• UNIQUE
• PRIMARY KEY
• FOREIGN KEY
• CHECK
• DEFAULT

1. NOT NULL: Ensures that we cannot leave a column as null. That is a value has to be supplied for that
column.
e.g name varchar(25) not null;
2. UNIQUE: Constraint means that the values under that column are always unique.
e.g Roll_no number(3) unique;
3. PRIMARY KEY: Constraint means that a column can not have duplicate values and not even a null
value.
e.g. Roll_no number(3) primary key;
The main difference between unique and primary key constraint is that a column specified as unique may
have null value but primary key constraint does not allow null values in the column.
4. FOREIGN KEY: Is used to enforce referential integrity and is declared as a primary key in some other
table.
e.g cust_id varchar(5) references master(cust_id);

it declares cust_id column as a foreign key that refers to cust_id field of table master. That means we
cannot insert that value in cust_id filed whose corresponding value is not present in cust_id field of
master table.
5. CHECK: Constraint limits the values that can be inserted into a column of a table.
e.g marks number(3) check(marks>=0);

The above statement declares marks to be of type number and while inserting or updating the value in
marks it is ensured that its value is always greater than or equal to zero.
6. DEFAULT: Constraint is used to specify a default value to a column of a table automatically. This default
value will be used when user does not enter any value for that column.
e.g balance number(5) default 0;

8. SQL COMMANDS (cont…)


INSERT command
• Syntax: insert into <tablename> [(<column i, . . . , column j>)] values (<value i, . . . , value j>);
• Example: INSERT INTO student VALUES(101,'Rohan','XI',400,‘Chennai');
INSERT INTO student VALUES (102,'Aneeta','XII',90,‘Benaluru');
SELECT COMMAND
• SELECT * FROM student;
Above command will display all the tuples in the relation student
• SELECT * FROM student WHERE Roll_no <=102;
The above command display only those records whose Roll_no less than or equal to 102.
• SELECT name, class FROM student;
The above command displays only name and class attributes from student table.
• SELECT count(*) AS “Total Number of Records” FROM student;
Display the total number of records with title as “Total Number of Records” i.e an alias

We can also use arithmetic operators in select statement, like


• SELECT Roll_no, name, marks+20 FROM student;
• SELECT name, (marks/500)*100 FROM student WHERE Roll_no > 103;
• SELECT name FROM student WHERE class=’XII’ AND name=’Anita’ ;

• Eliminating Duplicate/Redundant data


DISTINCT keyword is used to restrict the duplicate rows from the results of a SELECT statement.
e.g. SELECT DISTINCT name FROM student;
The above command returns,
Name
Rohan
Aneeta
Pawan Kumar

• Conditions based on a range


SQL provides a BETWEEN operator that defines a range of values that the column value must fall
for the condition to become true.
e.g. SELECT Roll_no, name
FROM student
WHERE Roll_no BETWEEN 100 AND 103;
The above command displays Roll_no and name of those students whose Roll_no lies in the range
100 to 103 (both 100 and 103 are included in the range).

• Conditions based on a list


To specify a list of values, IN operator is used. This operator select values that match any value in
the given list.
e.g. SELECT * FROM student WHERE city IN (‘Bengaluru’,’Delhi’,’Chennai’);
The above command displays all those records whose city is either Bengaluru or Delhi or Chennai

• Conditions based on Pattern


SQL provides two wild card characters that are used while comparing the strings with LIKE
operator.
a. percent ( % ) Matches any string
b. Underscore ( _ ) Matches any one character
e.g SELECT Roll_no, name, city FROM student WHERE Roll_no LIKE “%3”;
displays those records where last digit of Roll_no is 3 and may have any number of characters in
front.
e.g SELECT Roll_no, name, city FROM student WHERE Roll_no LIKE “1_3”;
displays those records whose Roll_no starts with 1 and second letter may be any letter but ends
with digit 3.

• Searching for NULL


The NULL value in the column can be searched using IS NULL in the where clause.
e.g. SELECT name, roll_no
FROM student
WHERE class IS NULL;

• ORDER BY Clause
ORDER BY clause is used to display the result of a query in a specific order(sorted order).
The sorting can be done in ascending or in descending order. It should be kept in mind that the
actual data in the database is not sorted but only the results of the query are displayed in sorted
order.
e.g. SELECT name, city FROM student ORDER BY name;
The above query returns name and city columns of table student sorted by name in
increasing/ascending order.
SELECT * FROM student ORDER BY city DESC;
It displays all the records of table student ordered by city in descending order.
Note:- If order is not specifies that by default the sorting will be performed in ascending
order.
• DELETE command
Delete command removes the rows from the table. It removes the entire row.
Syntax: DELETE FROM <tablename>
[WHERE clause];

e.g: DELETE FROM student


WHERE name=”Rohan”;
NOTE: To remove all the contents of STUDENT table, use the command:
DELETE FROM student;

• UPDATE and SET command


Update command is used to change some values in the existing row.
E:g UPDATE student
SET marks=400
WHERE name=’Sanjay’;

• ALTER TABLE Command


In SQL if we ever need to change the structure of the database then ALTER TABLE command is
used. By using this command we can add a column in the existing table, delete a column from a
table or modify columns in a table.
➢ Adding a column
The syntax to add a column is:-
ALTER TABLE <table_name>
ADD COLUMN<column_name>< datatype>;

e.g ALTER TABLE student


ADD COLUMN Address varchar(30);
The above command add a column Address to the table student.

➢ Removing a column
ALTER TABLE <table_name>
DROP COLUMN <column_name>;

e.g ALTER TABLE Student


DROP COLUMN Address;

• DROP TABLE Command


DROP TABLE <table_name>;
e.g DROP TABLE student;
• GROUP BY Clause
The GROUP BY clause can be used in a SELECT statement to collect data across multiple records and group the results
by one or more columns.
The syntax for the GROUP BY clause is:
SELECT column1, column2, ... column_n, aggregate_function (expression)
FROM tables
GROUP BY column1, column2, ... column_n;

aggregate_function can be a function such as SUM, COUNT, MAX, MIN, AVG etc.
e.g SELECT name, COUNT(*)
FROM student
GROUP BY city;
• HAVING Clause
The HAVING clause is used in combination with the GROUP BY clause.
E:g SELECT SUM(marks) as "Total marks"
FROM student
GROUP BY city
HAVING city=’Delhi’;

• Aggregate Functions available in SQL


Mathematical functions
Some of the commonly used mathematical functions are :
• sum()
• avg()
• count()
• min()
• max()

e.g. SELECT sum(marks) FROM student;


Displays the sum of all the marks in the table student.

e.g. SELECT min(Roll_no), max(marks) FROM student;


displays smallest Roll_no and highest marks in the table student.

• Cartesian Product
SELECT *
FROM emp, dept;

• JOINS
JOIN clause is used to combine rows from two or more tables, based on a related column between them.
e.g: SELECT name,salary,DName
FROM Emplyee,Department
WHERE Employee.Dept=Department.Dept;
PRACTICE QUESTIONS
Consider the tables given below and answer the questions that follow:

Table: Employee
EmpId Name Salary Zone Age Grade Dept
1 Mukul 30000 West 28 A 10
2 Kritika 35000 Centre 30 A 10
3 Naveen 32000 West 40 20
4 Uday 38000 North 38 C 30
5 Nupur 32000 East 26 20
6 Moksh 37000 South 28 B 10
7 Shelly 36000 North 26 A 30

Table: Department
Dept DName MinSal MaxSal HOD
10 Sales 25000 32000 1
20 Finance 30000 50000 5
30 Admin 25000 40000 7
Write SQL commands to:
Create Table
1. Create the table Employee.
2. Create the table Department.
Insert data in a table
3. Insert data in the table Employee
4. Insert data in the table Department.
Simple Select
5. Display the details of all the employees.
6. Display the Salary, Zone, and Grade of all the employees.
7. Display the records of all the employees along with their annual salaries. The Salary
column of the table contains monthly salaries of the employees.
8. Display the records of all the employees along with their annual salaries. The Salary
column of the table contains monthly salaries of the employees. The new column
should be given the name “Annual Salary”.
Conditional Select using Where Clause
9. Display the details of all the employees who are below 30 years of age.
10. Display the names of all the employees working in North zone.
11. Display the salaries of all the employees of department 10.

Using NULL
12. Display the details of all the employees whose Grade is NULL.
Using DISTINCT Clause
13. Display the names of various zones from the table Employee. A zone name should
appear only once.
Using Logical Operators (NOT, AND, OR)
14. Display the details of all the employees of department 10 who are above 30 years of
age.
15. Display the details of all the employees who are getting a salary of more than 35000 in
the department 30.
16. Display the names and salaries of all the employees who are not working in department
20.
17. Display the names and salaries of all the employees who are working neither in West
zone nor in Centre zone.

18. Display the names of all the employees who are working in department 20 or 30.
19. Display the details of all the employees whose salary is between 32000 and 38000.
20. Display the details of all the employees whose grade is between ‘A’ and ‘C’.
21. Display the details of all the employees aged above 30 in West zone.
Using IN Operator
22. Display the names of all the employees who are working in department 20 or 30.
(Using IN operator)
23. Display the names and salaries of all the employees who are working neither in West
zone nor in Centre
zone. (Using IN operator)
Using BETWEEN Operator
24. Display the details of all the employees whose salary is between 32000 and 38000.
(Using BETWEEN operator)
25. Display the details of all the employees whose grade is between ‘A’ and ‘C’.
(Using BETWEEN operator)
Using LIKE Operator
26. Display the name, salary, and age of all the employees whose names start with ‘M’.
27. Display the name, salary, and age of all the employees whose names end with ‘a’.
28. Display the name, salary, and age of all the employees whose names contain ‘a’
29. Display the name, salary, and age of all the employees whose names do not contain ‘a’
30. Display the details of all the employees whose names contain ‘a’ as the second
character.
Using Aggregate functions
31. Display the sum and average of the salaries of all the employees.
32. Display the highest and the lowest salaries being paid in department 10.
33. Display the number of employees working in department 10.
Using ORDER BY clause
34. Display the details of all the employees in the ascending order of their salaries.
35. Display the details of all the employees in the descending order of their names.
Using UPDATE, DELETE, ALTER TABLE
36. Put the grade B for all those whose grade is NULL.
37. Increase the salary of all the employees above 30 years of age by 10%.
38. Delete the records of all the employees whose grade is C and salary is below 30000.
39. Add another column HireDate of type Date in the Employee table.

You might also like