You are on page 1of 16

MY SQL

Index
1. Introduction to Database and RDBMS 2.

What is Database?
A database is a separate application that stores a collection of data. Each database has one or more distinct APIs for creating, accessing, managing, searching and replicating the data it holds. Other kinds of data stores can be used, such as files on the file system or large hash tables in memory but data fetching and writing would not be so fast and easy with those types of systems. So nowadays, we use relational database management systems (RDBMS) to store and manage huge volume of data. This is called relational database because all the data is stored into different tables and relations are established using primary keys or other keys known as foreign keys. A Relational DataBase Management System (RDBMS) is a software that: Enables you to implement a database with tables, columns and indexes. Guarantees the Referential Integrity between rows of various tables. Updates the indexes automatically. Interprets an SQL query and combines information from various tables.

RDBMS Terminology:
Before we proceed to explain MySQL database system, let's revise few definitions related to database. Database: A database is a collection of tables, with related data. Table: A table is a matrix with data. A table in a database looks like a simple spreadsheet. Column: One column (data element) contains data of one and the same kind, for example the column postcode. Row: A row (= tuple, entry or record) is a group of related data, for example the data of one subscription. Redundancy: Storing data twice, redundantly to make the system faster. Primary Key: A primary key is unique. A key value cannot occur twice in one table. With a key, you can find at most one row. Foreign Key: A foreign key is the linking pin between two tables. Compound Key: A compound key (composite key) is a key that consists of multiple columns, because one column is not sufficiently unique. Index: An index in a database resembles an index at the back of a book. Referential Integrity: Referential Integrity makes sure that a foreign key value always points to an existing row.

MySQL Database:
MySQL is the most popular Open Source Relational SQL database management system. MySQL is one of the best RDBMS being used for developing web-based software applications. MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses. MySQL is developed, marketed, and supported by MySQL AB, which is a Swedish company. MySQL is becoming so popular because of many good reasons:

MySQL is released under an open-source license. So you have nothing to pay to use it. MySQL is a very powerful program in its own right. It handles a large subset of the functionality of the most expensive and powerful database packages. MySQL uses a standard form of the well-known SQL data language. MySQL works on many operating systems and with many languages including PHP, PERL, C, C++, JAVA, etc. MySQL works very quickly and works well even with large data sets. MySQL is very friendly to PHP, the most appreciated language for web development. MySQL supports large databases, up to 50 million rows or more in a table. The default file size limit for a table is 4GB, but you can increase this (if your operating system can handle it) to a theoretical limit of 8 million terabytes (TB). MySQL is customizable. The open-source GPL license allows programmers to modify the MySQL software to fit their own specific environments.

Downloading MySQL:
All downloads for MySQL are located at MySQL Downloads. Pick the version number for MySQL Community Server you want and, as exactly as possible, the platform you want.

Installing MySQL on Windows:


Default installation on any version of Windows is now much easier than it used to be, as MySQL now comes neatly packaged with an installer. Simply download the installer package, unzip it anywhere, and run setup.exe. Default installer setup.exe will walk you through the trivial process and by default will install everything under C:\mysql. Test the server by firing it up from the command prompt the first time. Go to the location of the mysqld server which is probably C:\mysql\bin, and type: mysqld.exe --console

Administrative MySQL Command:


Here is the list of important MySQL commands, which you will use time to time to work with MySQL database:

USE Databasename : This will be used to select a particular database in MySQL workarea. SHOW DATABASES: Lists the databases that are accessible by the MySQL DBMS. SHOW TABLES: Shows the tables in the database once a database has been selected with the use command. SHOW COLUMNS FROM tablename: Shows the attributes, types of attributes, key information, whether NULL is permitted, defaults, and other information for a table. SHOW INDEX FROM tablename: Presents the details of all indexes on the table, including the PRIMARY KEY.

MySQL works very well in combination of various programming languages like PERL, C, C++, JAVA and PHP. Out of these languages, PHP is the most popular one because of its web application development capabilities.

Running Mysql on Command Prompt:

Creating database and showing Database:


Create Database command: This command is used to create a new database. Syntax: Mysql> create database <database name> eg: Mysql> create database school;

Showing Existing databaseUse Database command : is used to show existing data base syntax: Mysql>use <database name> eg: Mysql> use school;

MySQL Data Types:Data type CHAR(size) VARCHAR(size) Description Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is specified in parenthesis. Can store up to 255 characters Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 characters. Note: If you put a greater value than 255 it will be converted to a TEXT type Holds a string with a maximum length of 255 characters Holds a string with a maximum length of 65,535 characters For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data Holds a string with a maximum length of 16,777,215 characters For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data Holds a string with a maximum length of 4,294,967,295 characters For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data Let you enter a list of possible values. You can list up to 65535 values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted. Note: The values are sorted in the order you enter them. You enter the possible values in this format: ENUM('X','Y','Z') SET Similar to ENUM except that SET may contain up to 64 list items and can store more than one choice

TINYTEXT TEXT BLOB MEDIUMTEXT MEDIUMBLOB LONGTEXT LONGBLOB ENUM(x,y,z,etc.)

Number types: Data type TINYINT(size) SMALLINT(size) Description -128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be specified in parenthesis -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of

digits may be specified in parenthesis MEDIUMINT(size) INT(size) BIGINT(size) -8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number of digits may be specified in parenthesis -2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum number of digits may be specified in parenthesis -9223372036854775808 to 9223372036854775807 normal. 0 to 18446744073709551615 UNSIGNED*. The maximum number of digits may be specified in parenthesis A small number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter A large number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter A DOUBLE stored as a string , allowing for a fixed decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter

FLOAT(size,d)

DOUBLE(size,d)

DECIMAL(size,d)

Date types: Data type DATE() Description A date. Format: YYYY-MM-DD Note: The supported range is from '1000-01-01' to '9999-12-31' DATETIME() *A date and time combination. Format: YYYY-MM-DD HH:MM:SS Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59' TIMESTAMP() *A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD HH:MM:SS Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC TIME() A time. Format: HH:MM:SS Note: The supported range is from '-838:59:59' to '838:59:59' YEAR() A year in two-digit or four-digit format. Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in twodigit format: 70 to 69, representing years from 1970 to 2069

The CREATE TABLE statement is used to create a table in a database. Tables are organized into rows and columns; and each table must have a name. SQL CREATE TABLE Syntax CREATE TABLE table_name ( column_name1 data_type(size), column_name2 data_type(size), column_name3 data_type(size), .... ); The column_name parameters specify the names of the columns of the table. The data_type parameter specifies what type of data the column can hold (e.g. varchar, integer, decimal, date, etc.).

The size parameter specifies the maximum length of the column of the table. SQL Constraints SQL constraints are used to specify rules for the data in a table. If there is any violation between the constraint and the data action, the action is aborted by the constraint. Constraints can be specified when the table is created (inside the CREATE TABLE statement) or after the table is created (inside the ALTER TABLE statement). SQL CREATE TABLE + CONSTRAINT Syntax CREATE TABLE table_name ( column_name1 data_type(size) constraint_name, column_name2 data_type(size) constraint_name, column_name3 data_type(size) constraint_name, .... ); In SQL, we have the following constraints: NOT NULL - Indicates that a column cannot store NULL value UNIQUE - Ensures that each row for a column must have a unique value PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a column (or combination of two or more columns) have an unique identity which helps to find a particular record in a table more easily and quickly FOREIGN KEY - Ensure the referential integrity of the data in one table to match values in another table CHECK - Ensures that the value in a column meets a specific condition DEFAULT - Specifies a default value when specified none for this column

SQL NOT NULL Constraint The NOT NULL constraint enforces a column to NOT accept NULL values. The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert a new record, or update a record without adding a value to this field. The following SQL enforces the "P_Id" column and the "LastName" column to not accept NULL values: CREATE TABLE PersonsNotNull ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) ); SQL UNIQUE Constraint The UNIQUE constraint uniquely identifies each record in a database table. The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it. Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table. CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), UNIQUE (P_Id) ); SQL PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a database table. Primary keys must contain unique values. A primary key column cannot contain NULL values. Each table should have a primary key, and each table can have only ONE primary key. CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), PRIMARY KEY (P_Id) ); SQL FOREIGN KEY Constraint A FOREIGN KEY in one table points to a PRIMARY KEY in another table. Let's illustrate the foreign key with an example. Look at the following two tables: The "Persons" table:

P_Id LastName 1 2 3 Hansen Svendson Pettersen

FirstName Address Ola Tove Kari Timoteivn 10 Borgvn 23 Storgt 20

City Sandnes Sandnes Stavanger

The "Orders" table: O_Id OrderNo P_Id 1 2 3 4


`

77895 44678 22456 24562

3 3 2 1

Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons" table. The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table. The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table. The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables. The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign key column, because it has to be one of the values contained in the table it points to

CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, PRIMARY KEY (O_Id), FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) )

SQL INSERT INTO Syntax

It is possible to write the INSERT INTO statement in two forms.

SQL Statements Select the all column in the table Persons. SELECT * FROM Persons

Show the P_ID,LastName,Address from Persons Table

The WHERE Clause


The WHERE clause is used to extract only those records that fulfill a specified criterion

The AND & OR Operators:The AND & OR operators are used to filter records based on more than one condition.
The AND operator displays a record if both the first condition and the second condition is true

The OR operator displays a record if either the first condition or the second condition is true.

Combining AND & OR


You can also combine AND and OR (use parenthesis to form complex expressions). Now we want to select only the persons with the last name equal to "Nilsen" AND the first name equal to "John" OR to "Ola":

The ORDER BY Keyword:The ORDER BY keyword is used to sort the result-set by a specified column. The ORDER BY keyword sort the records in ascending order by default.

If you want to sort the records in a descending order, you can use the DESC keyword.

The UPDATE Statement


The UPDATE statement is used to update existing records in a table. Now we want to update the person address amitnagar in the "Persons" table.

The LIKE Operator


The LIKE operator is used to search for a specified pattern in a column. Now we want to select the persons living in a city that starts with "s" from the table above

Next, we want to select the persons living in a city that ends with an "s" from the "Persons" table.

we want to select the persons living in a city that contains the pattern "tav" from the "Persons" table.

It is also possible to select the persons living in a city that NOT contains the pattern "tav" from the "Persons" table, by using the NOT keyword.

Now we want to select the persons living in a city that starts with "sa" from the "Persons" table.

Next, we want to select the persons living in a city that contains the pattern "nes" from the "Persons" table.

The BETWEEN Operator


The BETWEEN operator selects a range of data between two values. The values can be numbers, text, or dates.

To display the persons outside the range in the previous example, use NOT BETWEEN:

SQL Aggregate Functions


SQL aggregate functions return a single value, calculated from values in a column. Useful aggregate functions:

AVG() - Returns the average value COUNT() - Returns the number of rows FIRST() - Returns the first value LAST() - Returns the last value MAX() - Returns the largest value MIN() - Returns the smallest value

SUM() - Returns the sum

SQL Scalar functions


SQL scalar functions return a single value, based on the input value. Useful scalar functions:

UCASE() - Converts a field to upper case LCASE() - Converts a field to lower case MID() - Extract characters from a text field LEN() - Returns the length of a text field ROUND() - Rounds a numeric field to the number of decimals specified NOW() - Returns the current system date and time

FORMAT() - Formats how a field is to be displayed

The AVG() Function


The AVG() function returns the average value of a numeric column.

Now we want to find the customers that have an OrderPrice value higher than the average OrderPrice value.

SQL COUNT() Function


The COUNT() function returns the number of rows that matches a specified criteria.

Now we want to count the number of orders from "Customer Nilsen".

The MAX() Function


The MAX() function returns the largest value of the selected column.

The MIN() Function


The MIN() function returns the smallest value of the selected column.

The SUM() Function


The SUM() function returns the total sum of a numeric column.

The LCASE() Function


The LCASE() function converts the value of a field to lowercase.

The MID() Function


The MID() function is used to extract characters from a text field.

The LEN() Function


The LEN() function returns the length of the value in a text field.

You might also like