This document provides an overview of key MySQL commands and SQL concepts for creating and managing databases and tables, inserting and modifying data, and performing queries. It covers creating databases and tables, defining data types, inserting records, selecting data with queries using operators like WHERE and BETWEEN, joining tables, altering and deleting tables, and more. The document is a tutorial for learning the basic syntax and functionality of the MySQL query language.
This document provides an overview of key MySQL commands and SQL concepts for creating and managing databases and tables, inserting and modifying data, and performing queries. It covers creating databases and tables, defining data types, inserting records, selecting data with queries using operators like WHERE and BETWEEN, joining tables, altering and deleting tables, and more. The document is a tutorial for learning the basic syntax and functionality of the MySQL query language.
Ex: >use school; 3. Create Tables in Mysql Create Table Command is used to create a new relation or table . When table is created we defined attribute (Column/Field) name ,data type and width (size) Ex: >create table student (rollno int,name char(50), Class char(5), sec char(2)); 4.Inserting Data into Table The Tuples (Rows/Record) are added to relation using INSERT INTO command Ex: > insert into student values (10,’amit’,’xii’,’a’); If change order of values then it is compulsory you mention attribute name also in insert into command Ex: > insert into student (name,rollno, sec,Class) values (‘amit’,10,’a’,’xii’); 5. Inserting NULL value: If you insert blank values in a attribute use NULL (capital without quotes) Ex: > insert into student (name,rollno, sec,Class) values (‘amit’,10,NULL,’xii’); 6. Simple Quires Through Select Command The select statement is use to fetch information from table Ex: > select name from student; 7. Selecting All attributes To Select All Field or Column use astrike sign (*) Ex: > select * from student; 8. Selecting Particular Rows (Where Clause) You can select particular row or rows with the help of where clause it is used to give condition here we can use Relation operator: Less then < ,Greater then > , Equal to =, Not Equal <>, Less then equal <=, Greater then equal >= Ex: >select * from student where name=’amit’; >select rollno,class where rollno>=30; >select name,Class,Sec where Class<>’xii’; Logical Operator: AND, OR, NOT Ex: >select * from student where Class=’x’ or Class=’xii’; >select name from student where rollno>=20 and rollno<=50; 9. Avoiding Duplicate values (Distinct ) Distinct keyword is used to avoid duplicate values Ex: >select distinct(class) from student; 10. All Keyword All is just opposite of distinct (without All keyword we got same output so it is just only syntax clarifier nothing). Ex: >select all(class) from student; 11.Searching NULL Vlaue To Search Null (Blank) values Ex: >select * from student where sec IS NULL; (show only those record where sec is not given) >select * from student where sec IS NOT NULL; (show only those record where sec is given) 12. IN Operator The IN operator selects values that match any value in a given list of values Ex: > select * from student where Class IN (‘ix’,’xi’); >select * from student where Class NOT IN (‘ix’,’xi’); 13. Between Operator The Between Operator defiones a range of values that the column values must fall in to make the condition true. Ex: >select name,rollno from student where rollno between 30 and 50; >select name,rollno from student where rollno NOT between 30 and 50; 14 . Aliases (AS Keyword) If you want to change the name of column only on output you can use As keyword Ex: >Select name as “Student Name” from student; 15. Like Operator (Wild Card character % and _ ) If you applying condition on string values then we use LIKE Operator here we use two special wild card characters: Percent (%) The % character matches any character and any no of character Underscore (_)The _ character matches any character and only one character Ex: > Select * from student where name like ‘a%’; (display all record where name started with char ‘a’) > Select * from student where name like ‘a___’; (display all record where name started with char ‘a’ max 4 char) 16. Performing Simple Calculation To perform simple calculation, you can write the expression/formula to be calculate next to keyword select Ex: > Select 4*5; 17. Rename attribute (AS Keyword) You can change the column name i.e column alias name with the help of AS keyword only output purpose Ex: >Select name as ‘Student Name’ from student; >Select 4*5 as ‘area’ ;
18 Data type in MySql
MySQL uses many different data types broken into three categories − Numeric Date and Time String Types. Numeric INT − A normal-sized integer that can be signed or unsigned. the allowable range is from -2147483648 to 2147483647. TINYINT − A very small integer range is from -128 to 127. SMALLINT − A small integer that can be range is from -32768 to 32767 MEDIUMINT − A medium-sized integer the allowable range is from -8388608 to 8388607. BIGINT − A large integer that can the allowable range is from -9223372036854775808 to 9223372036854775807 FLOAT(M,D) − A floating-point number that cannot be unsigned. 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 DOUBLE(M,D) − A double precision floating-point number default to 16,4, Date and Time DATE − A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For example, December 30th, 1973 would be stored as 1973-12-30. DATETIME − A date and time combination in YYYY-MM-DD HH:MM:SS format, between 1000-01-01 00:00:00 and 9999-12-31 23:59:59. For example, 3:30 in the afternoon on December 30th, 1973 would be stored as 1973-12-30 15:30:00. TIMESTAMP − A timestamp between midnight, January 1st, 1970 and sometime in 2037. This looks like the previous DATETIME format, only without the hyphens between numbers; 3:30 in the afternoon on December 30th, 1973 would be stored as 19731230153000 ( YYYYMMDDHHMMSS ). TIME − Stores the time in a HH:MM:SS format. YEAR(M) − Stores a year in a 2-digit or a 4-digit format. If the length is specified as 2 (for example YEAR(2)), YEAR can be between 1970 to 2069 (70 to 69). If the length is specified as 4, then YEAR can be 1901 to 2155. The default length is 4. String Types CHAR(M) − A fixed-length string between 1 and 255 characters in length (for example CHAR(5)), right-padded with spaces to the specified length when stored. Defining a length is not required, but the default is 1. VARCHAR(M) − A variable-length string between 1 and 255 characters in length. For example, VARCHAR(25). You must define a length when creating a VARCHAR field. BLOB or TEXT − A field with a maximum length of 65535 characters. BLOBs are "Binary Large Objects" and are used to store large amounts of binary data, such as images or other types of files. Fields defined as TEXT also hold large amounts of data. The difference between the two is that the sorts and comparisons on the stored data are case sensitive on BLOBs and are not case sensitive in TEXT fields. You do not specify a length with BLOB or TEXT. TINYBLOB or TINYTEXT − A BLOB or TEXT column with a maximum length of 255 characters. You do not specify a length with TINYBLOB or TINYTEXT. MEDIUMBLOB or MEDIUMTEXT − A BLOB or TEXT column with a maximum length of 16777215 characters. You do not specify a length with MEDIUMBLOB or MEDIUMTEXT. LONGBLOB or LONGTEXT − A BLOB or TEXT column with a maximum length of 4294967295 characters. You do not specify a length with LONGBLOB or LONGTEXT. ENUM − An enumeration, which is a fancy term for list. When defining an ENUM, you are creating a list of items from which the value must be selected (or it can be NULL). For example, if you wanted your field to contain "A" or "B" or "C", you would define your ENUM as ENUM ('A', 'B', 'C') and only those values (or NULL) could ever populate that field. 19. Creating Table with SQL Constraints The following constraints are commonly used in SQL: NOT NULL - Ensures that a column cannot have a NULL value UNIQUE - Ensures that all values in a column are different PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table FOREIGN KEY - Uniquely identifies a row/record in another table CHECK - Ensures that all values in a column satisfies a specific condition DEFAULT - Sets a default value for a column when no value is specified INDEX - Used to create and retrieve data from the database very quickly Ex:>CREATE TABLE teacher(ID int NOT NULL,name varchar(50) NOT NULL,age int); > CREATE TABLE teacher(ID int NOT NULL,name varchar(50) UNIQUE,age int); >CREATE TABLE teacher(ID int NOT NULL UNIQUE,name varchar(50) ,age int); >CREATE TABLE teacher(ID int PRIMARY KEY,name varchar(50) ,age int); >CREATE TABLE teacher(ID int ,name varchar(50) ,age int, PRIMARY KEY (ID),FOREIGN KEY (staffID) REFERENCES staff(staffID)); >CREATE TABLE teacher(ID int NOT NULL,name varchar(50) UNIQUE,age int CHECK (Age>=18)); >CREATE TABLE teacher(ID int UNIQUE,name varchar(50),age int, city varchar(255) DEFAULT 'Agra'); >CREATE TABLE teacher(ID int NOT NULL,name varchar(50),age int, INDEX teacheridx(ID)); 20. Viewing a Table Structue To display structure of a table use desc or describe command Ex: > Desc teacher; or >Describe teacher; 21. Removing Table (Drop Command) To Remove relation physically from your storage device use DROP Command Ex: >drop table student; 22. Inserting Data into another Table Inserting command can also be used to take drive values from one table and place them in another by using it with a query. Ex: > insert into table1 values select * from table2 where name=’amit’; 23. Delete Row’s from Table To remove record or records you can use DELETE commands . This remove entire rows not individual field or values. Ex: > Delete from student where name like ‘amit’; >Delete from student where roll>=50; 24.Modifying Data in Tables You can modify data in tables using UPDATE command of sql. Ex: >update student set roll=99 where name=’amit’; >update student set per=per+10 where class=’xii’; 25. Altering Tables It is very powerful command this is used to change definitions of existing tables. Only this command you can Add ,Modify ,Change and drop attribute. Ex: > Alter table student ADD (per float); >Alter table student MODIFY name char(20); >Alter table student CHANGE name Stuname char(56); >Alter table student drop per; 26.SQl Join An SQL Join is a that featches data from two or more tables whose records are joined with one another based on condition. Ex: >select student.name ,student1.name from student,student1 where student.class=student1.class; 27. Ordering Data ( Arrange row in Ascending or Descending order) If you want to sort record into ascending or descending order you can use ORDER BY Clause . Keywords ASC and DESC denote the order Ascending and Descending .By Default it is ASC i.e Ascending order. Ex: >Select * from student order by name asc; >select * from student order by roll; >select * from student order by roll desc; >select * from student order by name asc, roll desc; 28. Aggregates Function List of aggregate functions . COUNT() We use the COUNT function to find the number of rows matching the given condition Ex: >select count(*) from student; OR >select count(*) from student where class=’xii’; >select count(class) from student; >select count (distinct class) from student; MIN () We use the MIN function to find the minimum value. Ex: >select min(roll) from student; MAX () We use the MAX function to find the maximum value. Ex: >select max(roll) from student; AVG() We use the AVG function to find the average. Ex: >select avg(roll) from student; SUM () We use the SUM function to find the sum. Ex: >select sum(roll) from student; 29 . Grouping Result (GROUP BY CLAUSE) The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of student in each Class". Ex: >Select count(*) from student GROUP BY class; 30. Placing Conditions on Group- HAVING Clause The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions. Ex: >Select count(*) from student GROUP BY class HAVING count(*)>1; 31. MySql Function MySQL has many built-in functions.This reference contains string, numeric, and date functions in MySQL. MySQL String Functions (i) UCASE()/UPPER() :Convert the text to upper-case: Ex: >SELECT UCASE("Vset Technology"); OR > SELECT UCASE(name) from student; (ii) LCASE()/LOWER() :Convert the text to lower-case: Ex: >SELECT LCASE("Vset Technology"); OR > SELECT LCASE(name) from student; (iii) LENGTH () : Return the length of the string, in bytes: Ex: >SELECT LENGTH ("Vset Technology"); OR > SELECT LENGTH(name) from student; (iv) LEFT () : function extracts a number of characters from a string (starting from left). Ex: >SELECT LEFT("Vset Technology",4); OR > SELECT LEFT(name,4) from student; (v) RIGHT () : function extracts a number of characters from a string (starting from right). Ex: >SELECT RIGHT("Vset Technology",10); OR > SELECT RIGHT(name,5) from student; (vi) SUBSTRING(): function extracts a substring from a string (starting at any position). The SUBSTR() and MID() functions equals to the SUBSTRING() function. Ex: >SELECT SUBSTR ("Vset Technology",6,4); OR > SELECT SUBSTR(name,6,4) from student; (vii) INSTR():function returns the position of the first occurrence of a string in another string. This function performs a case- insensitive search. Ex: >SELECT INSTR("Vset Technology",”Tech”); OR > SELECT SUBSTR(name,”a”) from student; (viii) TRIM():function removes leading and trailing spaces from a string. Ex: >SELECT TRIM(" Vset Technology "); OR > SELECT TRIM(name) from student; (ix) LTRIM():function removes leading spaces from a string. Ex: >SELECT LTRIM(" Vset Technology "); OR > SELECT LTRIM(name) from student; (x) RTRIM():function removes trailing spaces from a string. Ex: >SELECT RTRIM(" Vset Technology "); OR > SELECT RTRIM(name) from student; MySQL Numeric Functions (i) POWER()/POW() :function returns the value of a number raised to the power of another number. Ex: >SELECT POWER (2,5); (ii) ROUND() :function function rounds a number to a specified number of decimal places. Ex: >SELECT ROUND(3.87324,0); OR > SELECT PRICE,ROUND(PRICE,2)as “New Price” from LOAN; (iii) MOD() : function returns the remainder of a number divided by another number. Ex: >SELECT MOD(73,2); OR > SELECT 73%2; MySQL Date Functions (i) NOW() : Return current date and time. Ex: >SELECT NOW(); (ii) DATE() : function extracts the date part from a datetime expression. Ex: >SELECT DATE("2017-06-15 09:34:21"); OR >SELECT DATE(NOW()); OR > SELECT DATE(DOB) from student; (iii) MONTH() : Return the month part of a date. Ex: >SELECT MONTH("2017-06-15 09:34:21"); OR >SELECT MONTH(NOW());OR > SELECT MONTH (DOB) from student; (iv) MONTHNAME() : function returns the name of the month for a given date. Ex: >SELECT MONTHNAME("2017-06-15 09:34:21"); OR >SELECT MONTHNAME(NOW());OR > SELECT MONTHNAME(DOB) from student; (v) YEAR() : function returns the year part for a given date (a number from 1000 to 9999). Ex: >SELECT YEAR("2017-06-15 09:34:21"); OR >SELECT YEAR(NOW());OR > SELECT YEAR (DOB) from student; (v) DAY() : function returns the day of the month for a given date (a number from 1 to 31). Ex: >SELECT DAY("2017-06-15 09:34:21"); OR >SELECT DAY(NOW());OR > SELECT DAY (DOB) from student; (v) DAYNAME() : function returns the weekday name for a given date. Ex: >SELECT DAYNAME("2017-06-15 09:34:21"); OR >SELECT DAYNAME(NOW());OR > SELECT DAYNAME(DOB) from student;