0% found this document useful (0 votes)
8 views16 pages

CSK W MySQL NOTES - 1 (INFO)

Chapter 8 discusses MySQL, a popular open-source relational database management system (RDBMS) that utilizes Structured Query Language (SQL) for data management. It covers key features of MySQL, including its open-source nature, security, and various SQL command categories such as DDL, DML, TCL, and DCL. Additionally, it explains how to create databases and tables, insert data, and utilize various SQL commands for data retrieval and manipulation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views16 pages

CSK W MySQL NOTES - 1 (INFO)

Chapter 8 discusses MySQL, a popular open-source relational database management system (RDBMS) that utilizes Structured Query Language (SQL) for data management. It covers key features of MySQL, including its open-source nature, security, and various SQL command categories such as DDL, DML, TCL, and DCL. Additionally, it explains how to create databases and tables, insert data, and utilize various SQL commands for data retrieval and manipulation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Chapter 8

MySQL
SQL (Structured Query Language)
The database management system(DBMS) is a special kind of programming language
called a query language to enable users to access data from the database. Structured
Query Language (SQL) is the language used by most relational database systems
(RDBMS). It is a standard language developed and used for accessing and modifying
relational databases
The SQL language was originally developed at the IBM research laboratory in San José,
in connection with a project developing a prototype for a relational database management
system called System R in the early 70s.
SQL is being used by many database management systems. Some of them are:
 MySQL
 PostgreSQL
 Oracle
 SQLite
 Microsoft SQL Server
MYSQL
Mysql is currently the most popular open-source database software. It is a multi-user,
multiprocessing database management system.
Mysql is one of the best RDBMS being used for developing various web-based software
applications.
Mysql AB was founded by Michael Widenius(Monty), David Axmark and Allan Larsson
in Sweden in the year 1995.
Mysql is an Open Source, Fast and Reliable Relational Database Management System
(RDBMS) . MySQL is free to use, and you can download it from MySQL official
website( http://www.mysql.com/).

The main features of MySQL are:


Open Source & Free of Cost: It is Open Source and available at free of cost.
Portability: It can be installed and run on any type of Hardware and OS, like Linux.
MS Windows or Mac etc.
Security: Its Databases are secured & protected with a password. It offers privilege and
Password system for authorisation.
Connectivity: It may connect various types of clients using different protocols and
Programming Languages.
Query Language: It supports SQL (Structured Query Language) for accessing and
modifying relational databases.
MySQL Commands:
Structured Query Language is a programming language designed to manage data stored
in relational databases.
SQL commands are grouped into four major categories depending on their functionality:

Data Definition Language (DDL)


DDL commands are used for creating, modifying, and dropping the physical structure of
database objects.
Examples : CREATE, ALTER, DROP, RENAME

Data Manipulation Language (DML)


DML commands are used for storing, retrieving, modifying, and deleting data.
Example : SELECT, INSERT, UPDATE, and DELETE.

Transaction Control Language (TCL)


These SQL commands are used for managing changes done through DML commands.
Example COMMIT, ROLLBACK, and SAVEPOINT.
Data Control Language (DCL)
These SQL commands are used to provide security to database objects.
These commands are GRANT and REVOKE

MySQL COMMANDS
The database management system(DBMS) is a special kind of programming language
called a query language to enable users to access data from the database. Structured
Query Language (SQL) is the language used by most of the relational database systems
(RDBMS). Mysql is currently the most popular and common open-source database
software for database management. Mysql provides commands for defining, modifying,
controlling and deleting the databases and relations.
 CREATE Database :
To create a database, we use the CREATE DATABASE statement.
syntax: CREATE DATABASE databasename;
To create a database called School, we will type the following command at Mysql prompt.
mysql> CREATE DATABASE School;
To create a database called LIBRARY,
mysql> CREATE DATABASE LIBRARY;
A DBMS can manage multiple databases on one computer. Therefore, we need to select
the database that we want to use. Once the database is selected, we can proceed with
creating tables or querying data.
 To open/ activate/ use the existing database,
Syntax: mysql> USE databasename;
mysql> USE School;
 To get the list of existing databases of Mysql server,
mysql> SHOW DATABASES;
Initially, the created database was empty. It can be checked by using the Show tables
command, which lists the names of all the tables within a database.
 To get the list of existing tables in a database,
mysql> SHOW TABLES;
 To remove/delete the existing database,
Syntax: mysql> DROP DATABASE databasename;
mysql> DROP DATABASE School;

 Creating Tables - CREATE TABLE Command


After creating the database School, we need to define relations (create tables) in this
database and specify attributes for each relation, along with data types for each attribute.
This is done using the CREATE TABLE statement.
It is important to observe the following points with respect to the Create Table statement:
• N is the degree of the relation, means there are N columns in the table.
• Attribute name specifies the name of the column in the table.
• Datatype specifies the type of data that an attribute can hold.
• Constraint indicates the restrictions imposed on the values of an attribute.

Character Set of MySQL


A set of valid characters recognised by Mysql Interpreter.
A character represents any letter, digit or any other symbol.
Mysql uses the Unicode character set; ASCII characters are a subset of Unicode
characters.
 Letters : A-Z, a-z (treated as the same)
 Digits : 0-9
 Special symbols : Special symbols available over keyboard like @, %, *, :, etc.
 White spaces:– blank space, tab, carriage return, new line.
 Other characters:- Python can process all ASCII characters and Unicode characters
as part of data.

Attribute / column Naming


• A column name starts with a letter A to Z or a to z or an underscore (_) followed by
letters, underscores and digits (0 to 9).
• MySQL does not allow special characters($, @, *, +, ?, : ) in column names.
• Attributes must not be a keyword (words have special meaning for Mysql interpreters
like create, use, select, delete, show etc.) of Mysql.
• Mysql is not a case-sensitive language (meaning both upper- and lower-case letters are
considered the same).
• Column name can be any size (Preferably 8 characters).
• Column name should be meaningful and self-explanatory.
Here are some examples of acceptable identifiers:
1. Price 2. Mark_1 3. Total_mark 4. Firstname 5. DisPRICE 6.
subject5

Examples of invalid identifier, write the reason for invalidity:


1. int 2. Rno. 3. $Price 4. 5subject 5. Total Amount 6.SUM 7. unit-price
Data Types in MySQL:
Mysql database consists of one or more relations, and each relation (table) is made up of
attributes (columns). Each attribute has a data type.
Data type indicates the type of data value that an attribute can have. The data type of an
attribute decides the operations that can be performed on the data of that attribute. For
example, arithmetic operations(+, -,*, / ) can be performed on numeric data but not on
character data. Commonly used data types in Mysql are numeric types, date and time
types, and string (character / Text) types.
Null value: SQL supports a special value called NULL to represent a data missing,
unknown value or empty space. It is important to note that NULL is different from 0
(zero). Also, any arithmetic operation performed with a NULL value gives NULL.
E.g. 5 + NULL = NULL

Data type in MySQL

 Numeric Data Types:


 INTEGER or INT or NUMBER – up to an 11-digit number without decimal.
 INTEGER(p) or INT(p) or NUMBER(p) - up to precision p digits integer.
 SMALLINT – up to a 5-digit number without decimal.
 BIGINT -up to 19-digit numbers without decimal.
 FLOAT (M, D) or DECIMAL(M, D) or NUMERIC(M, D) or NUMBER(M, D) - Stores
Real numbers up to M digit length (including decimal point) with D decimal places.
e.g. Float (10,2) can store 1234567.89
 String, Text or Character Data Type:
 CHAR(Size) - A fixed-length string up to 255 characters. (Default 1)
 VARCHAR(Size) - A variable-length string up to 255 characters.
 Date & Time Data Types:
 TIME - Store time in HH:MM: SS format.
 DATE - Store date in YYYY-MM-DD format.
Char, Varchar, Date and Time values should be enclosed with single (‘ ‘) or double ( “”)
quotes in Mysql. Varchar is used in Mysql and varchar2 is used in Oracle.

Difference between CHAR and VARCHAR datatypes


CHAR VARCHAR

CHAR datatype is used to store VARCHAR datatype is used to store


character strings of fixed length character strings of variable length

In CHAR, if the length of the string is In VARCHAR, if the length of the


less string is less than the set or fixed
than the set or fixed length, then it is length, then it will store as it is
padded with extra memory space. without being padded with extra
memory spaces.

The storage size of the CHAR datatypes The storage size of the VARCHAR
is equal to n bytes i.e. set length datatype is equal to the actual length
of the entered string in bytes.

CHAR takes 1 byte for each character VARCHAR takes 1 byte for each
character and some extra bytes for
holding length information

Better performance than VARCHAR Performance is not as good as


compared to CHAR
Conclusion: VARCHAR saves space when there is variation in the length of
values, but CHAR might be performance-wise better.

Constraints
Constraints are certain types of restrictions on the data values that an attribute can have.
They are used to ensure the accuracy and reliability of data. However, it is not mandatory
to define constraint for each attribute of a table.
 By default, each attribute can take NULL values except for the primary key.
 Not NULL and Unique constraints, when applied together, will produce a Primary Key
constraint.
 Unique constraint allows one Null value for the attribute.

 Creating Tables - CREATE TABLE Command [DDL Command]


To define relations/ create the structure(schema) of a table in an existing database, and
specify attribute name, data type, size and constraint for each attribute, we can use the
CREATE TABLE statement/command.

Column Name Data Type Size/ Width


Admno integer 5
Name varchar 15
Class_Sec varchar 7
DOB date -
Per_Mark Float 6,2
mysql> CREATE TABLE student
( Admno integer(5),
Name varchar(15),
Class_Sec varchar(7),
DOB date,
Per_Mark float(6,2) );

Creating Table with Constraints:


mysql> CREATE TABLE student
(Admno integer(5) Primary key,
Name varchar(15) not null,
Class_Sec varchar(7) default “ XI- A”,
DOB date,
Per_Mark float(6,2) check (Per_Mark >=0 and Per_mark<=100) );

DESCRIBE Command
DESCRIBE is used to view the structure/ Schema of an existing table.
Syntax: mysql> DESCRIBE Tablename;
mysql> DESCRIBE student;

INSERT INTO command :


INSERT INTO command: inserting/ adding a new row into an existing table.
Syntax: mysql> INSERT INTO tablename values(value 1, value 2, ………value n);
mysql> INSERT INTO student values( 15046, ’ALEENA’,’XI-C’, ’2009-05-22’,95.75);

To insert record with specific column values only


Syntax: mysql> INSERT INTO tablename ( column name1, column name 2,………)
values(value 1, value 2, ………value n);
mysql> INSERT INTO student(Admno, Name, Per_Mark, Dob)
values( 15672, ‘Sunil’, 93.25, ’2009-12-25’ );
SELECT Command [DML Command]
The SQL statement SELECT is used to retrieve data from the tables in a database and the
output is also displayed in tabular form.

 1. To select/retrieve all rows from the table


Syntax: mysql> SELECT * FROM table_name ;
The FROM clause is always written with the SELECT clause, as it specifies the name of
the table from which data is to be retrieved.
mysql> SELECT * FROM student;
Above command retrieve data from all rows and columns from the table student.

Eg:- To display details of all employees from the table EMP.


mysql> SELECT * FROM emp;

 2 . To select/display the data from specified columns


Syntax: mysql> SELECT attribute1, attribute2, ... FROM table_name ;
Here, attribute1, attribute2, ... are the column names of the table from which we want to
retrieve data.
mysql> SELECT Admno, Name, Per_mark from student ;
Above command displays Admno, name and Per_mark of all the students from the table
Student.

To display employee number, name, job, and salary of all employees from the table EMP
mysql> SELECT Empno, Ename, job, Salary from Emp ;
 3. DISTINCT Clause/ Keyword

By default, SQL shows all the data retrieved through the query as output. However, there
can be duplicate values. The SELECT statement, when combined with the DISTINCT
clause, returns records without repetition (distinct records) or eliminates duplicate values
of the specified column.
Syntax: mysql> SELECT DISTINCT attribute FROM Table name;
For example, while retrieving an employee’s job, there can be duplicate values as many
employees are assigned to the same job. To display a unique job type for all the
employees, we use DISTINCT as shown below:
mysql> SELECT DISTINCT Job FROM EMP;

 4. WHERE Clause/ Keyword


The WHERE clause is used to retrieve data (rows) that meet some specified conditions.
Relational operators <, <=, >, >=, =, !=, or <>(not equal) can be used to specify such
conditions on columns. The logical operators AND, OR, and NOT are used to combine
multiple conditions.
Syntax: mysql> SELECT attribute1, attribute2, ... FROM table_name
WHERE Condition;
To display the details of employees getting a salary of more than 2000,
mysql> SELECT * from emp
where salary > 2000;
To display details of clerks from the table EMP,
mysql> SELECT * from emp
where job = “clerk” ;

To display the employee name, job, and salary of employees working in department 20,
mysql> SELECT ename, job, salary, deptno from emp
where deptno= 20 ;

To display employee name , job , salary of employees other than salesmen,


mysql> SELECT ename, job, salary from emp
where job <> “salesman” ;

 5. WHERE Clause with multiple conditions


The logical operators AND, OR, and NOT are used to combine multiple conditions to
retrieve rows from the tables using select …… where condition.
To display the details of employees getting a salary between 1500 and 3500,
mysql> SELECT * from emp
where salary >= 1500 and salary<=3500;

To display details of clerks and managers from the table EMP,


mysql> SELECT * from emp
where job = “clerk” or job=“manager” ;

To display the employee name, job, and salary of employees other than managers,
mysql> SELECT ename, job, salary from emp
where not job = “manager” ;

To display the employee name, job, salary,deptno of employees working in department


20 or 30 and getting a salary of more than 3000.
mysql> SELECT ename, job, salary, deptno from emp
where deptno= 20 or deptno=30 and salary >3000;

Conditions-based operators
Conditions based on a range:-SQL provides a BETWEEN/NOT BETWEEN operator that
defines a range of values that the column value must fall for the condition to become true.
E.g., write an SQL command to display the name and salary of all the employees whose
earnings are between 2000 and 3000
SELECT ENAME, SALARY FROM EMP
WHERE SALARY BETWEEN 2000 AND 3000;
The above command displays Ename and salary of those employees whose salary lies in the
range 2000 to 3000 (both 2000 and 3000 are included in the range).
E.g., write an SQL command to display the name & salary of all the employees whose salary
is less than 2000 or more than 3000
SELECT ENAME, SALARY FROM EMP
WHERE SALARY NOT BETWEEN 2000 AND 3000;
Conditions based on a list: To specify a list of values, the IN/NOT IN operator is used. This
operator selects values that match any value in the given list.
Eg:- Write SQL commands to display the details of employees who are working as CLERKS,
MANAGERS or ANALYSTS.

SELECT * FROM EMP WHERE


JOB IN(‘CLERK’,’MANAGER’,’ANALYST’);
E.g., write SQL commands to display the details of employees other than CLERKS,
MANAGERS and ANALYSTS.

SELECT * FROM EMP WHERE


JOB NOT IN(‘CLERK’,’MANAGER’,’ANALYST’);
Conditions based on Pattern:- SQL provides two wild card characters that are used while
comparing the strings with the LIKE/NOT LIKE operator.
a. percent(%) Matches any string(Represents a substring in any length)
b. Underscore(_)Matches any one character
Write a SQL command to display the details of employees whose names start with A
SELECT * FROM EMP
WHERE ENAME LIKE ‘A%’;
Example:
‘A%’ represents any string starting with the ‘A’ character.
‘_ _A’ represents any 3-character string ending with ‘A’.
‘_B%’ represents any string having the second character ‘B’
‘_ _ _’ represents any 3-letter string.
A pattern is case sensitive and can be used with the LIKE operator.
mysql> SELECT * FROM emp WHERE EName NOT LIKE ‘A%’;
mysql> SELECT * FROM emp WHERE EName LIKE ’%S%’;
mysql> SELECT EName FROM emp WHERE EName NOT LIKE‘%r %’;
SEARCHING FOR NULL - The NULL value in a column can be searched for in a table
using IS NULL/ IS NOT NULL operator.
Write the SQL command to display the details of employees who are not getting a
Commission.
SELECT * FROM EMP
WHERE COMM IS NULL;
Write the SQL command to display the details of employees are getting commissions.
SELECT * FROM EMP
WHERE COMM IS NOT NULL;
Using Mathematical operators in the select command
Write the SQL command to display the EMPNO,ENAME & SALARY by adding Rs.
100 to all the Employees as BONUS
SELECT EMPNO,ENAME,SAL+100 as BONUS FROM EMP;
Write the SQL command to display the EMPNO, ENAME, SALARY, and COMM by
adding the SALARY and COMM of all the Employees as TOTAL_SALARY for those
who are getting a COMM.
SELECT EMPNO, ENAME, SAL+COMM as TOTAL_SALARY FROM EMP
WHERE COMM IS NOT NULL;
Arranging rows using ORDER BY:- Mysql Order By clause is used to sort the table data in
either Ascending order or descending order, the default is ascending.
The ORDER BY clause is used as :
SELECT, …. FROM WHERE condition ORDER BY column ;
Eg: To display the details of employees in the EMP table in alphabetical order
SELECT * FROM EMP ORDER BY ENAME;
To display a list of employees in descending alphabetical order whose salary is greater than
3000.
SELECT * FROM EMP
WHERE SALARY > 3000 ORDER BY ENAME desc ;
Write a SQL command to display the details of employees whose SALARY is more than
1000, according to the JOB and ENAME in reverse alphabetical order.
SELECT EMPNO,ENAME, JOB, SAL FROM EMP
WHERE SAL>1000 ORDER BY JOB, ENAME desc;
MODIFYING DATA IN TABLES: You can modify data in tables using the UPDATE
command of SQL. The UPDATE command specifies the rows to be changed using the
WHERE clause, and the new data using the SET keyword.
Syntax : UPDATE SET col.name=value WHERE condition;
e.g. To change the salary of employees in the EMP table having employee no.7839 to 4500.
UPDATE EMP SET SALARY = 4500
WHERE EMPNO = 7839;
UPDATING MORE THAN ONE COLUMN
e.g. To update the salary to 5800 and DEPTNO to 30 for those employees whose employee
ENAME is SCOTT.
UPDATE EMP SET SALARY = 5800, DEPTNO=30
WHERE ENAME=’SCOTT’;
Write the SQL command to increase the salary of all the employees in the table EMP by
5% of salary, whose salary of more than 2000
UPDATE EMP SET SALARY=SALARY+SALARY*5/100

WHERE SALARY>2000;

DELETE COMMAND: Used to delete all or Selected Rows from the table. The delete
command belongs to the DML category.
SYNTAX: DELETE FROM TABLE NAME WHERE CONDITION;
Write the SQL command to delete the details of CLERKS from table EMP.
DELETE FROM EMP WHERE JOB=’CLERK’;
Write the SQL command to delete all rows from the table EMP.
DELETE FROM EMP ;
DROPPING TABLES: The DROP TABLE command removes a table(both rows and
structure) from the database. This command belongs to the DDL category.
Syntax: DROP TABLE tablename ;
E.g. To drop a table EMP,
DROP TABLE EMP;
Once this command is given, the table name is no longer recognized, and all the data in the
table along with the table structure will be deleted.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy