SQL commands-converted
SQL commands-converted
Create Table: This command is used to create a new table in the Database. You must be in
the same database where you want to create the table.(DDL)
Syntax: CREATE TABLE table_name (column1 datatype, column2 datatype, column3
datatype)
Example. CREATE TABLE Persons ( PersonID int, LastName varchar(255))
Drop Table: Drop a Table. The drop table command is used to delete a table and all rows
in the table. To delete an entire table including all of its rows, issue the drop
table command followed by the tablename. Dropping the table removes the table definition
as well as all of its rows.(DDL)
Syntax:DROP TABLE table_name;
Example: DROP TABLE PERSONS;
Alter Table:
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an existing
table.(DDL)
Let us first see the Add column:
Update ....Set....,
The SQL UPDATE Query is used to modify the existing records in a table. You can use the
WHERE clause with the UPDATE query to update the selected rows, otherwise all the rows
would be affected.
Syntax:
The basic syntax of the UPDATE query with a WHERE clause is as follows −
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
You can combine N number of conditions using the AND or the OR operators.
Example:
Syntax
There are two basic syntaxes of the INSERT INTO statement which are shown below.
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
Here, column1, column2, column3,...columnN are the names of the columns in the table into
which you want to insert the data.
You may not need to specify the column(s) name in the SQL query if you are adding values
for all the columns of the table. But make sure the order of the values is in the same order as
the columns in the table.
The SQL INSERT INTO syntax will be as follows −
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
Example
The following statements would create six records in the CUSTOMERS table.
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );
You can create a record in the CUSTOMERS table by using the second syntax as shown
below.
INSERT INTO CUSTOMERS
VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );
Populate one table using another table:
You can populate the data into a table through the select statement over another table;
provided the other table has a set of fields, which are required to populate the first table.
Here is the syntax −
INSERT INTO first_table_name [(column1, column2, ... columnN)]
SELECT column1, column2, ...columnN
FROM second_table_name
[WHERE condition];
Example: insert into selected as select * from test_marks where marks>50;
The SQL DELETE Statement:
The DELETE statement is used to delete existing records in a table.
Syntax:
DELETE FROM table_name WHERE condition;
Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE
statement. The WHERE clause specifies which record(s) should be deleted. If you omit the
WHERE clause, all records in the table will be deleted!
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Customer CustomerName ContactName Address City PostalCode Country
ID
1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany
Futterkiste
2 Ana Trujillo Ana Trujillo Avda. de la México 5021 Mexico
Emparedados y Constitución D.F.
helados 2222
3 Antonio Moreno Antonio Mataderos México 5023 Mexico
Taquería Moreno 2312 D.F.
4 Around the Thomas 120 Hanover London WA1 1DP UK
Horn Hardy Sq.
Example
The following SQL statement deletes the customer "Alfreds Futterkiste" from the
"Customers" table:
Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
Select:
The SQL SELECT Statement
The SELECT statement is used to select data from a database.
The data returned is stored in a result table, called the result-set.
SELECT Syntax
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data from. If
you want to select all the fields available in the table, use the following syntax:
SELECT * FROM table_name;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Customer CustomerName ContactName Address City PostalCode Country
ID
1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany
Futterkiste
2 Ana Trujillo Ana Trujillo Avda. de la México 5021 Mexico
Emparedados y Constitución D.F.
helados 2222
3 Antonio Moreno Antonio Mataderos México 5023 Mexico
Taquería Moreno 2312 D.F.
4 Around the Thomas 120 Hanover London WA1 1DP UK
Horn Hardy Sq.
Inside a table, a column often contains many duplicate values; and sometimes you only want
to list the different (distinct) values.
SELECT DISTINCT Syntax
SELECT DISTINCT column1, column2, ...
FROM table_name;
Demo Database:Below is a selection from the "Customers" table in the Northwind sample
database:
Customer CustomerName ContactName Address City PostalCode Country
ID
1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany
Futterkiste
2 Ana Trujillo Ana Trujillo Avda. de la México 5021 Mexico
Emparedados y Constitución D.F.
helados 2222
3 Antonio Moreno Antonio Mataderos México 5023 Mexico
Taquería Moreno 2312 D.F.
4 Around the Thomas 120 Hanover London WA1 1DP UK
Horn Hardy Sq.
The following SQL statement selects the "CustomerName" and "City" columns from the
"Customers" table:
Example
SELECT CustomerName, City FROM Customers;
The following SQL statement selects all the columns from the "Customers" table:
Example
SELECT * FROM Customers;Try it Yourself »
The following SQL statement deletes the customer "Alfreds Futterkiste" from the
"Customers" table:
Example
DELETE FROM Customers
WHERE CustomerName='Alfreds Futterkiste';
IN Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
The following SQL statement selects all customers that are located in "Germany", "France"
or "UK":
Example
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
The SQL BETWEEN Operator:
The BETWEEN operator selects values within a given range. The values can be numbers,
text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2
The following SQL statement selects all products with a price BETWEEN 10 and 20:
Example
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards often used in conjunction with the LIKE operator:
• % - The percent sign represents zero, one, or multiple characters
• _ - The underscore represents a single character
• The percent sign and the underscore can also be used in combinations!
• LIKE Syntax
• SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Tip: You can also combine any number of conditions using AND or OR operators.
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
LIKE Operator Description
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position
WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are at least 2
characters in length
WHERE CustomerName LIKE 'a__%' Finds any values that start with "a" and are at least 3
characters in length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with "o"
The following SQL statement selects all customers with a CustomerName starting with "a":
Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
The following SQL statement selects all customers with a CustomerName ending with "a":
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';
The following SQL statement selects all customers with a CustomerName that have "or" in
any position:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
The following SQL statement selects all customers with a CustomerName that starts with "a"
and are at least 3 characters in length:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';
Null / is Null:
What is a NULL Value?
A field with a NULL value is a field with no value.If a field in a table is optional, it is
possible to insert a new record or update a record without adding a value to this field. Then,
the field will be saved with a NULL value.
A NULL value is different from a zero value or a field that contains spaces. A field with a
NULL value is one that has been left blank during record creation!
How to Test for NULL Values?
We will have to use the IS NULL and IS NOT NULL operators instead.
IS NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
The IS NULL Operator
The IS NULL operator is used to test for empty values (NULL values).
The following SQL lists all customers with a NULL value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
The IS NOT NULL Operator
IS NOT NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).
The following SQL lists all customers with a value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
Order by :
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records
in descending order, use the DESC keyword.
Syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Example
The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" column:
SELECT * FROM Customers
ORDER BY Country;
ORDER BY DESC Example
The following SQL statement selects all customers from the "Customers" table, sorted
DESCENDING by the "Country" column:
SELECT * FROM Customers
ORDER BY Country DESC;
ORDER BY Several Columns Example
The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" and the "CustomerName" column. This means that it orders by Country, but if
some rows have the same Country, it orders them by CustomerName:
SELECT * FROM Customers
ORDER BY Country, CustomerName;
ORDER BY Several Columns Example 2
The following SQL statement selects all customers from the "Customers" table, sorted
ascending by the "Country" and descending by the "CustomerName" column:
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
The SQL GROUP BY Statement:
The GROUP BY statement groups rows that have the same values into summary rows, like
"find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN,
SUM, AVG) to group the result-set by one or more columns.
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Demo table:
CustomerID CustomerName ContactName Address City PostalCode Country
The following SQL statement lists the number of customers in each country:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
The following SQL statement lists the number of customers in each country, sorted high to
low:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
The following SQL statement lists the number of customers in each country. Only include
countries with more than 5 customers:
We will use the products and orderdetails tables from the sample database for demonstration:
MySQL aggregate function – AVG() function examples
The AVG() function calculates the average value of a set of values. It ignores NULL in the
calculation.
AVG(expression)
For example, you can use the AVG function to calculate the average buy price of all products
in the products table by using the following query:
SELECT
AVG(buyPrice) average_buy_price
FROM
products;
The following statement uses the COUNT() function with the GROUP BY clause to get the
number of products for each product line:
SELECT
productLine,
COUNT(*)
FROM
products
GROUP BY productLine
ORDER BY productLine;
The SUM() function returns the sum of values in a set. The SUM() function ignores NULL. If
no matching row found, the SUM() function returns NULL.
To get the total order value of each product, you can use the SUM() function in conjunction
with the GROUP BY clause as follows:
SELECT
productCode,
SUM(priceEach * quantityOrdered) total
FROM
orderDetails
GROUP BY productCode
ORDER BY total DESC;
The following statement uses the MAX() function with the GROUP BY clause to get the
highest price per product line:
SELECT
productLine, MAX(buyPrice)
FROM
products
GROUP BY productLine
ORDER BY MAX(buyPrice) DESC;
A SQL Join statement is used to combine data or rows from two or more tables based on a
common field between them.
What is Equi Join in SQL?
SQL EQUI JOIN performs a JOIN against equality or matching column(s) values of the
associated tables. An equal sign (=) is used as comparison operator in the where clause to
refer equality.
Syntax:
SELECT column_list
FROM table1, table2....
WHERE table1.column_name =
table2.column_name;
Example:
Here is an example of Equi Join in SQL.
Sample table: agents
AGENT_CODE ,AGENT_NAME , WORKING_AREA , COMMISSION, PHONE_NO ,
COUNTRY
Sample table: customer
,CUST_CODE , CUST_NAME , CUST_CITY , WORKING_AREA ,
CUST_COUNTRY , GRADE , OPENING_AMT , RECEIVE_AMT , PAYMENT_AMT
,OUTSTANDING_AMT , PHONE_NO , AGENT_CODE
To get agent name column from agents table and cust name and cust city columns from
customer table after joining said two tables with the following condition -
1. working area of agents and customer city of customer table must be same,
the following SQL statement can be used:
SQL Code:
SELECT agents.agent_name,customer.cust_name,
customer.cust_city
FROM agents,customer
WHERE agents.working_area=customer.cust_city;
Output:
AGENT_NAME CUST_NAME CUST_CITY
---------------------------------------- ---------------------------------------- ------------
Ravi Kumar Ravindran Bangalore
Ramasundar Ravindran Bangalore
Subbarao Ravindran Bangalore
Ravi Kumar Srinivas Bangalore
Ramasundar Srinivas Bangalore
Subbarao Srinivas Bangalore
Ravi Kumar Rangarappa Bangalore
Ramasundar Rangarappa Bangalore
Subbarao Rangarappa Bangalore
Ravi Kumar Venkatpati Bangalore
Ramasundar Venkatpati Bangalore
Subbarao Venkatpati Bangalore
Anderson Fleming Brisban
Anderson Jacks Brisban
Anderson Winston Brisban
Santakumar Yearannaidu Chennai
Natural Join
The NATURAL JOIN is a type of EQUI JOIN and is structured in such a way that, columns
with the same name of associated tables will appear once only. - The associated tables have
one or more pairs of identically named columns. - The columns must be the same data type.
Natural Joins: The join in which one of the identical columns exist, is called Natural Join.
The natural join is much similar to Equi-Join, records are joined on the equality condition of
joining column except that the common column appears one time.
(After Natural Join following output will be produced)
: MySQL offer two ways by which you may join two or more tables.
One is using multiple tables with FROM clause and using JOIN keyword with FROM clause.
Joining multiple tables with FROM clause
Select * from Student, Stream where student.scode= stream.scode;