MySQL Prof.Sushila Aghav
Introduction SQL is a standard language for storing, manipulating and retrieving data in databases. SQL is a part of many relational database management systems like: MySQL, SQL Server, MS Access, Oracle, Sybase, Informix, Postgres, and other database systems.
RDBMS RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access. The data in RDBMS is stored in database objects called tables. A table is a collection of related data entries and it consists of columns and rows.
SQL SQL stands for Structured Query Language SQL lets you access and manipulate databases SQL can execute queries against a database SQL can retrieve data from a database SQL can insert records in a database SQL can update records in a database SQL can delete records from a database SQL can create new databases SQL can create new tables in a database SQL can create stored procedures in a database SQL can create views in a database SQL can set permissions on tables, procedures, and views
Sample Relation CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK 5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden
Database Language Commands SELECT - extracts data from a database UPDATE - updates data in a database DELETE - deletes data from a database INSERT INTO - inserts new data into a database CREATE DATABASE - creates a new database ALTER DATABASE - modifies a database CREATE TABLE - creates a new table ALTER TABLE - modifies a table DROP TABLE - deletes a table CREATE INDEX - creates an index (search key) DROP INDEX - deletes an index
Syntax : Create Database CREATE DATABASE databasename; The CREATE DATABASE statement is used to create a new SQL database. The DROP DATABASE statement is used to drop an existing SQL database. Example : CREATE DATABASE testdb; DROP DATABASE databasename; DROP DATABASE testdb;
CREATE TABLE Statement The CREATE TABLE statement is used to create a new table in a database. CREATE TABLE Persons ( PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255) ); INT,CHAR,VARCHAR,DATE DROP TABLE Persons;
Constraint : NOT NULL CREATE TABLE users( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR( 25 ) NOT NULL, last_name VARCHAR( 25 ) NOT NULL, age INT NOT NULL );
Constraint : CHECK CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int, CHECK (Age>=18) );
Constraint : DEFAULT CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int, City varchar(255) DEFAULT 'Sandnes' );
Constraint : UNIQUE CREATE TABLE Persons ( ID int NOT NULL UNIQUE, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int );
Constraint : Foreign Key CREATE TABLE Orders ( OrderID int NOT NULL, OrderNumber int NOT NULL, PersonID int, PRIMARY KEY (OrderID), FOREIGN KEY (PersonID) REFERENCES Persons(PersonID) );
AUTO_INCREMENT The following SQL statement defines the "ID" column to be an auto-increment primary key field in the "Persons" table: CREATE TABLE Persons ( ID int NOT NULL AUTO_INCREMENT, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int, PRIMARY KEY (ID) ); MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature. By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record. To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement: ALTER TABLE Persons AUTO_INCREMENT=100;
Alter Table ALTER TABLE Persons ADD DateOfBirth date; ALTER TABLE Persons DROP COLUMN DateOfBirth; ALTER TABLE table_name MODIFY COLUMN column_name datatype;
Index CREATE INDEX idx_lastname ON Persons (LastName); ALTER TABLE table_name DROP INDEX index_name;
View CREATE VIEW V1 AS SELECT ProductName, UnitPrice FROM Products; Select * from V1; DROP VIEW view_name;
Select SELECT column1, column2,... FROM table_name; SELECT * FROM table_name; SELECT DISTINCT column1, column2,... FROM table_name; SELECT * FROM Customers WHERE Country='Mexico';
Operators Operator Description = Equal <> Not equal. Note: In some versions of SQL this operator may be written as!= > Greater than < Less than >= Greater than or equal <= Less than or equal BETWEEN LIKE IN Between an inclusive range Search for a pattern To specify multiple possible values for a column
Examples SELECT * FROM Customers WHERE Country='Germany' AND City='Berlin'; SELECT * FROM Customers WHERE City='Berlin' OR City='München'; SELECT * FROM Customers WHERE NOT Country='Germany'; SELECT * FROM Customers WHERE Country='Germany' AND (City='Berlin' OR City='München');
Order by SELECT * FROM Customers ORDER BY Country; SELECT * FROM Customers ORDER BY Country DESC; SELECT * FROM Customers ORDER BY Country ASC, CustomerName DESC;
Insert Into INSERT INTO table_name VALUES (value1, value2, value3,...); INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country) VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger ); INSERT INTO Customers (CustomerName, City, Country) VALUES ('Cardinal', 'Stavanger', 'Norway'); '4006', 'Norway');
Checking with NULL SELECT LastName, FirstName, Address FROM Persons WHERE Address IS NULL; SELECT LastName, FirstName, Address FROM Persons WHERE Address IS NOT NULL;
Update UPDATE Customers SET ContactName = 'Alfred Schmidt', City= 'Frankfurt' WHERE CustomerID = 1; UPDATE Customers SET ContactName='Juan';
Delete DELETE FROM table_name WHERE condition; DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste'; DELETE FROM table_name;
Top records Retrieval SELECT column_name(s) FROM table_name WHERE condition LIMIT number; SELECT * FROM Customers LIMIT 3; SELECT * FROM Customers WHERE Country='Germany' LIMIT 3;
Min,Max,Sum,Avg,Count SELECT MIN(Price) AS SmallestPrice FROM Products; SELECT MAX(Price) AS LargestPrice FROM Products; SELECT AVG(Price) FROM Products; SELECT SUM(Quantity) FROM OrderDetails; SELECT COUNT(ProductID) FROM Products;
Like Operator SELECT * FROM Customers WHERE CustomerName LIKE 'a%'; LIKE Operator WHERE CustomerName LIKE 'a%' WHERE CustomerName LIKE '%a' WHERE CustomerName LIKE '%or%' WHERE CustomerName LIKE '_r%' WHERE CustomerName LIKE 'a_%_%' WHERE ContactName LIKE 'a%o' Description Finds any values that starts with "a" Finds any values that ends with "a" Finds any values that have "or" in any position Finds any values that have "r" in the second position Finds any values that starts with "a" and are at least 3 characters in length Finds any values that starts with "a" and ends with "o"
In, Between SELECT * FROM Customers WHERE Country IN ('Germany', 'France', 'UK'); SELECT * FROM Customers WHERE Country IN (SELECT Country FROM Suppliers); SELECT * FROM Products WHERE Price BETWEEN 10 AND 20; SELECT * FROM Products WHERE Price NOT BETWEEN 10 AND 20;