SQL Qyeries-1notes
SQL Qyeries-1notes
SQL tutorial provides basic and advanced concepts of SQL. Our SQL tutorial is designed for beginners and professionals.
SQL (Structured Query Language) is used to perform operations on the records stored in the database such as updating records,
deleting records, creating and modifying tables, views, etc.
SQL is just a query language; it is not a database. To perform SQL queries, you need to install any database, for example, Oracle,
MySQL, MongoDB, PostGre SQL, SQL Server, DB2, etc.
What is SQL
All DBMS like MySQL, Oracle, MS Access, Sybase, Informix, PostgreSQL, and SQL Server use SQL as standard database language.
SQL is required:
o With SQL, we can query our database in several ways, using English-like statements.
o With SQL, a user can access data from a relational database management system.
o It allows the user to describe the data.
o It allows the user to define the data in the database and manipulate it when needed.
o It allows the user to create and drop database and table.
o It allows the user to create a view, stored procedure, function in a database.
o It allows the user to set permission on tables, procedures, and views.
SQL Syntax
SQL follows some unique set of rules and guidelines called syntax. Here, we are providing all the basic SQL syntax.
o SQL is not case sensitive. Generally SQL keywords are written in uppercase.
o SQL statements are dependent on text lines. We can place a single SQL statement on one or multiple text lines.
o You can perform most of the action in a database with SQL statements.
o SQL depends on relational algebra and tuple relational calculus.
SQL statement
SQL statements are started with any of the SQL commands/keywords like SELECT, INSERT, UPDATE, DELETE, ALTER, DROP etc. and
the statement ends with a semicolon (;).
1. SELECT "column_name" FROM "table_name";
Semicolon is used to separate SQL statements. It is a standard way to separate SQL statements in a database system in which more
than one SQL statements are used in the same call.
In this tutorial, we will use semicolon at the end of each SQL statement.
SQL Commands
Data types mainly classified into three categories for every database.
A list of data types used in MySQL database. This is based on MySQL 8.0.
CHAR(Size) It is used to specify a fixed length string that can contain numbers, letters,
and special characters. Its size can be 0 to 255 characters. Default is 1.
VARCHAR(Size) It is used to specify a variable length string that can contain numbers,
letters, and special characters. Its size can be from 0 to 65535 characters.
BINARY(Size) It is equal to CHAR() but stores binary byte strings. Its size parameter
specifies the column length in the bytes. Default is 1.
VARBINARY(Size) It is equal to VARCHAR() but stores binary byte strings. Its size parameter
specifies the maximum column length in bytes.
TEXT(Size) It holds a string that can contain a maximum length of 255 characters.
ENUM(val1, val2, It is used when a string object having only one value, chosen from a list of
val3,...) possible values. It contains 65535 values in an ENUM list. If you insert a
value that is not in the list, a blank value will be inserted.
SET( val1,val2,val3,. It is used to specify a string that can have 0 or more values, chosen from a
...) list of possible values. You can list up to 64 values at one time in a SET list.
BLOB(size) It is used for BLOBs (Binary Large Objects). It can hold up to 65,535 bytes.
BIT(Size) It is used for a bit-value type. The number of bits per value is specified in size. Its
size can be 1 to 64. The default value is 1.
INT(size) It is used for the integer value. Its signed range varies from -2147483648 to
2147483647 and unsigned range varies from 0 to 4294967295. The size
parameter specifies the max display width that is 255.
INTEGER(size) It is equal to INT(size).
FLOAT(size, d) It is used to specify a floating point number. Its size parameter specifies the total
number of digits. The number of digits after the decimal point is specified
by d parameter.
DOUBLE(size, It is a normal size floating point number. Its size parameter specifies the total
d) number of digits. The number of digits after the decimal is specified by d
parameter.
DECIMAL(size, It is used to specify a fixed point number. Its size parameter specifies the total
d) number of digits. The number of digits after the decimal parameter is specified
by d parameter. The maximum value for the size is 65, and the default value is 10.
The maximum value for d is 30, and the default value is 0.
BOOL It is used to specify Boolean values true and false. Zero is considered as false, and
nonzero values are considered as true.
DATE It is used to specify date format YYYY-MM-DD. Its supported range is from
'1000-01-01' to '9999-12-31'.
DATETIME(fsp) It is used to specify date and time combination. Its format is YYYY-MM-DD
hh:mm:ss. Its supported range is from '1000-01-01 00:00:00' to 9999-12-31
23:59:59'.
TIMESTAMP(fsp It is used to specify the timestamp. Its value is stored as the number of seconds
) since the Unix epoch('1970-01-01 00:00:00' UTC). Its format is YYYY-MM-DD
hh:mm:ss. Its supported range is from '1970-01-01 00:00:01' UTC to '2038-01-
09 03:14:07' UTC.
TIME(fsp) It is used to specify the time format. Its format is hh:mm:ss. Its supported range
is from '-838:59:59' to '838:59:59'
YEAR It is used to specify a year in four-digit format. Values allowed in four digit
format from 1901 to 2155, and 0000.
SQL Server Data Types
char(n) It is a fixed width character string data type. Its size can be up to 8000 characters.
varchar(n) It is a variable width character string data type. Its size can be up to 8000
characters.
varchar(max It is a variable width character string data types. Its size can be up to 1,073,741,824
) characters.
text It is a variable width character string data type. Its size can be up to 2GB of text
data.
nchar It is a fixed width Unicode string data type. Its size can be up to 4000 characters.
nvarchar It is a variable width Unicode string data type. Its size can be up to 4000 characters.
ntext It is a variable width Unicode string data type. Its size can be up to 2GB of text data.
binary(n) It is a fixed width Binary string data type. Its size can be up to 8000 bytes.
varbinary It is a variable width Binary string data type. Its size can be up to 8000 bytes.
image It is also a variable width Binary string data type. Its size can be up to 2GB.
float(n) It is used to specify floating precision number data from -1.79E+308 to 1.79E+308. The n
parameter indicates whether the field should hold the 4 or 8 bytes. Default value of n is
53.
real It is a floating precision number data from -3.40E+38 to 3.40E+38.
datetime It is used to specify date and time combination. It supports range from January 1,
1753, to December 31, 9999 with an accuracy of 3.33 milliseconds.
datetime2 It is used to specify date and time combination. It supports range from January 1,
0001 to December 31, 9999 with an accuracy of 100 nanoseconds
date It is used to store date only. It supports range from January 1, 0001 to December 31,
9999
timestam It stores a unique number when a new row gets created or modified. The time stamp
p value is based upon an internal clock and does not correspond to real time. Each table
may contain only one-time stamp variable.
Sql_variant It is used for various data types except for text, timestamp, and ntext. It stores
up to 8000 bytes of data.
CHAR(size) It is used to store character data within the predefined length. It can be stored
up to 2000 bytes.
NCHAR(size) It is used to store national character data within the predefined length. It can
be stored up to 2000 bytes.
VARCHAR2(size) It is used to store variable string data within the predefined length. It can be
stored up to 4000 byte.
VARCHAR(SIZE) It is the same as VARCHAR2(size). You can also use VARCHAR(size), but it is
suggested to use VARCHAR2(size)
NVARCHAR2(size It is used to store Unicode string data within the predefined length. We have
) to must specify the size of NVARCHAR2 data type. It can be stored up to 4000
bytes.
NUMBER(p, s) It contains precision p and scale s. The precision p can range from 1 to 38, and
the scale s can range from -84 to 127.
FLOAT(p) It is a subtype of the NUMBER data type. The precision p can range from 1 to
126.
BINARY_FLOAT It is used for binary precision( 32-bit). It requires 5 bytes, including length byte.
BINARY_DOUBL It is used for double binary precision (64-bit). It requires 9 bytes, including
E length byte.
DATE It is used to store a valid date-time format with a fixed length. Its range varies from
January 1, 4712 BC to December 31, 9999 AD.
TIMESTAM It is used to store the valid date in YYYY-MM-DD with time hh:mm:ss format.
P
BLOB It is used to specify unstructured binary data. Its range goes up to 2 32-1 bytes or 4 GB.
BFILE It is used to store binary data in an external file. Its range goes up to 2 32-1 bytes or 4
GB.
CLOB It is used for single-byte character data. Its range goes up to 2 32-1 bytes or 4 GB.
NCLOB It is used to specify single byte or fixed length multibyte national character set
(NCHAR) data. Its range is up to 232-1 bytes or 4 GB.
RAW(size) It is used to specify variable length raw binary data. Its range is up to 2000 bytes per
row. Its maximum size must be specified.
LONG It is used to specify variable length raw binary data. Its range up to 2 31-1 bytes or 2
RAW GB, per row.
SQL Operators
SQL statements generally contain some reserved words or characters that are used to perform operations such as comparison and
arithmetical operations etc. These reserved words or characters are known as operators.
Let's assume two variables "a" and "b". Here "a" is valued 50 and "b" valued 100.
Example:
+ It is used to add containing values of both operands a+b will give 150
- It subtracts right hand operand from left hand operand a-b will give -50
/ It divides left hand operand by right hand operand b/a will give 2
% It divides left hand operand by right hand operand and returns b%a will give 0
reminder
Let's take two variables "a" and "b" that are valued 50 and 100.
= Examine both operands value that are equal or not,if yes condition (a=b) is not
become true. true
!= This is used to check the value of both operands equal or not,if not (a!=b) is true
condition become true.
<> Examines the operand's value equal or not, if values are not equal (a<>b) is true
condition is true
> Examine the left operand value is greater than right Operand, if yes (a>b) is not
condition becomes true true
< Examines the left operand value is less than right Operand, if yes (a<=""
condition becomes true td="">
>= Examines that the value of left operand is greater than or equal to the (a>=b) is not
value of right operand or not,if yes condition become true true
<= Examines that the value of left operand is less than or equal to the (a<=b) is true
value of right operand or not, if yes condition becomes true
!< Examines that the left operand value is not less than the right operand (a!<=""
value td="">
!> Examines that the value of left operand is not greater than the value of (a!>b) is true
right operand
C++ vs Java
Operator Description
ALL this is used to compare a value to all values in another value set.
AND this operator allows the existence of multiple conditions in an SQL statement.
ANY this operator is used to compare the value in list according to the condition.
BETWEEN this operator is used to search for values, that are within a set of values
NOT the NOT operator reverse the meaning of any logical operator
EXISTS the EXISTS operator is used to search for the presence of a row in a specified table
LIKE this operator is used to compare a value to similar values using wildcard operator
1. CREATE DATABASE database_name;
If you want to add tables in that database, you can use CREATE TABLE statement.
Create Database in MySQL
1. CREATE DATABASE database_name;
You don't need to create database in Oracle. In Oracle database, you can create tables directly.
You can also rename, drop and select database that is covered in next pages.
C++ vs Java
We should always remember that database name should be unique in the RDBMS.
If you want to delete or drop an existing database in a SQL schema, you can use SQL DROP DATABASE
1. DROP DATABASE database_name;
If you delete or drop the database, all the tables and views will also be deleted. So be careful while using this command.
To rename the mysql database, you need to follow the following syntax:
1. RENAME DATABASE old_db_name TO new_db_name;
Rename SQL server database using T-SQL
This command is useful for SQL server 2005, 2008, 2008R2 and 2012.
1. ALTER DATABASE old_name MODIFY NAME = new_name
If you are using SQL server 2000, you can also use this command to rename the database. But, Microsoft phased out it.
1. EXEC sp_renamedb 'old_name' , 'new_name'
1. USE DATABASE database_name;
SQL Table
Table is a collection of data, organized in terms of rows and columns. In DBMS term, table is known as relation and row as tuple.
Note: A table has a specified number of columns, but can have any number of rows.
Table is the simple form of data storage. A table is also considered as a convenient representation of relations.
Employee
In the above table, "Employee" is the table name, "EMP_NAME", "ADDRESS" and "SALARY" are the column names. The combination
of data of multiple columns forms a row e.g. "Ankit", "Lucknow" and 15000 are the data of one row.
The SQL Table variable is used to create, modify, rename, copy and delete tables. Table variable was introduced by Microsoft.
It was introduced with SQL server 2000 to be an alternative of temporary tables.
It is a variable where we temporary store records and results. This is same like temp table but in the case of temp table we need to
explicitly drop it.
Table variables are used to store a set of records. So declaration syntax generally looks like CREATE TABLE syntax.
1. create table "tablename"
2. ("column1" "data type",
3. "column2" "data type",
4. ...
5. "columnN" "data type");
When a transaction rolled back the data associated with table variable is not rolled back.
If you want to create a table, you should name the table and define its column and each column's data type.
1. create table "tablename"
2. ("column1" "data type",
3. "column2" "data type",
4. "column3" "data type",
5. ...
6. "columnN" "data type");
The data type of the columns may vary from one database to another. For example, NUMBER is supported in Oracle database for
integer value whereas INT is supported in MySQL.
Let us take an example to create a STUDENTS table with ID as primary key and NOT NULL are the constraint showing that these
fields cannot be NULL while creating records in the table.
1. SQL> CREATE TABLE STUDENTS (
2. ID INT NOT NULL,
3. NAME VARCHAR (20) NOT NULL,
4. AGE INT NOT NULL,
5. ADDRESS CHAR (25),
6. PRIMARY KEY (ID)
7. );
You can verify it, if you have created the table successfully by looking at the message displayed by the SQL Server, else you can use
DESC command as follows:
ID Int(11) NO PRI
NAME Varchar(20) NO
AGE Int(11) NO
ADDRESS Varchar(25) YES NULL
Now you have the STUDENTS table available in your database and you can use to store required information related to students.
1. CREATE TABLE Employee
2. (
3. EmployeeID int,
4. FirstName varchar(255),
5. LastName varchar(255),
6. Email varchar(255),
7. AddressLine varchar(255),
8. City varchar(255)
9. );
1. CREATE TABLE Employee
2. (
3. EmployeeID number(10),
4. FirstName varchar2(255),
5. LastName varchar2(255),
6. Email varchar2(255),
7. AddressLine varchar2(255),
8. City varchar2(255)
9. );
Let's see the command to create a table in SQLServer database. It is same as MySQL and Oracle.
1. CREATE TABLE Employee
2. (
3. EmployeeID int,
4. FirstName varchar(255),
5. LastName varchar(255),
6. Email varchar(255),
7. AddressLine varchar(255),
8. City varchar(255)
9. );
Create a Table using another table
We can create a copy of an existing table using the create table command. The new table gets the same column signature as the old
table. We can select all columns or some specific columns.
If we create a new table using an old table, the new table will be filled with the existing value from the
old table.
The basic syntax for creating a table with the other table is:
1. CREATE TABLE table_name AS
2. SELECT column1, column2,...
3. FROM old_table_name WHERE ..... ;
4. The following SQL creates a copy of the employee table.
5. CREATE TABLE EmployeeCopy AS
6. SELECT EmployeeID, FirstName, Email
7. FROM Employee;
The following query creates a PRIMARY KEY on the "D" column when the "Employee" table is created.
MySQL
1. CREATE TABLE Employee(
2. EmployeeID NOT NULL,
3. FirstName varchar(255) NOT NULL,
4. LastName varchar(255),
5. City varchar(255),
6. PRIMARY KEY (EmployeeID)
7. );
Use the following query to define a PRIMARY KEY constraints on multiple columns, and to allow naming of a PRIMARY KEY
constraints.
This is very important to know that once a table is deleted all the information available in the table is lost forever, so we have to be
very careful when using this command.
Let's see the syntax to drop the table from the database.
1. DROP TABLE "table_name";
First we verify STUDENTS table and then we would delete it from the database.
1. SQL> DESC STUDENTS;
ID Int(11) NO PRI
NAME Varchar(20) NO
AGE Int(11) NO
1. 4 rows in set (0.00 sec)
This shows that STUDENTS table is available in the database, so we can drop it as follows:
1. SQL>DROP TABLE STUDENTS;
Now, use the following command to check whether table exists or not.
1. SQL> DESC STUDENTS;
1. Query OK, 0 rows affected (0.01 sec)
Let's see the command to drop a table from the MySQL database.
1. DROP TABLE table_name;
SQL DROP TABLE Example in Oracle
Let's see the command to drop a table from Oracle database. It is same as MySQL.
1. DROP TABLE table_name;
Let's see the command to drop a table from SQLServer database. It is same as MySQL.
1. DROP TABLE table_name;
1. DELETE FROM table_name [WHERE condition];
But if you do not specify the WHERE condition it will remove all the rows from the table.
1. DELETE FROM table_name;
There are some more terms similar to DELETE statement like as DROP statement and TRUNCATE statement but they are not exactly
same there are some differences between them.
There is a slight difference b/w delete and truncate statement. The DELETE statement only deletes the rows from the table based on
the condition defined by WHERE clause or delete all the rows from the table when condition is not specified.
The TRUNCATE statement: it is used to delete all the rows from the table and free the containing space.
When you use the drop statement it deletes the table's row together with the table's definition so all the relationships of that table
with other tables will no longer be valid.
On the other hand when we TRUNCATE a table, the table structure remains the same, so you will not face any of the above
problems.
1. ALTER TABLE table_name
2. RENAME TO new_table_name;
1. RENAME old_table _name To new_table_name;
Let us take an example of a table named "STUDENTS", now due to some reason we want to change it into table name "ARTISTS".
Table1: students
You should use any one of the following syntax to RENAME the table name:
1. ALTER TABLE STUDENTS
2. RENAME TO ARTISTS;
Or
1. RENAME STUDENTS TO ARTISTS;
2. After that the table "students" will be changed into table name "artists"
Truncate table is faster and uses lesser resources than DELETE TABLE command.
Drop table command can also be used to delete complete table but it deletes table structure too. TRUNCATE TABLE doesn't delete
the structure of the table.
Let's see the syntax to truncate the table from the database.
1. TRUNCATE TABLE table_name;
For example, you can write following command to truncate the data of employee table
1. TRUNCATE TABLE Employee;
You can also use SQL ALTER TABLE command to add and drop various constraints on an existing table.
If you want to add columns in SQL table, the SQL alter table syntax is given below:
1. ALTER TABLE table_name ADD column_name column-definition;
If you want to add multiple columns in table, the SQL table will be
1. ALTER TABLE table_name
2. ADD (column_1 column-definition,
3. column_2 column-definition,
4. .....
5. column_n column-definition);
If you want to modify an existing column in SQL table, syntax is given below:
1. ALTER TABLE table_name MODIFY column_name column_type;
If you want to modify multiple columns in table, the SQL table will be
1. ALTER TABLE table_name
2. MODIFY (column_1 column_type,
3. column_2 column_type,
4. .....
5. column_n column_type);
1. ALTER TABLE table_name DROP COLUMN column_name;
1. ALTER TABLE table_name
2. RENAME COLUMN old_name to new_name;
SQL SELECT
The most commonly used SQL command is SELECT statement. It is used to query the database and retrieve selected data that
follow the conditions we want.
In simple words, we can say that the select statement used to query or retrieve data from a table in the database.
1. SELECT expressions
2. FROM tables
3. WHERE conditions;
[GROUP BY Clause] : Groups rows that share a property so that the aggregate function can be applied to each group.
[HAVING Clause] : It selects among the groups defined by the GROUP BY clause.
From the above example, select the first name of all the students. To do so, query should be like this:
1. SELECT first_name FROM student_details;
Note: the SQL commands are not case sensitive. We can also write the above SELECT statement as:
1. select first_name from student_details;
Akbar
Anthony
We can also retrieve data from more than one column. For example, to select first name and last name of all the students, you need
to write
1. SELECT first_name, last_name FROM student_details;
Amar Sharma
Akbar Khan
Anthony Milton
We can also use clauses like WHERE, GROUP BY, HAVING, ORDER BY with SELECT statement.
Here a point is notable that only SELECT and FROM statements are necessary in SQL SELECT statements. Other clauses like WHERE,
GROUP BY, ORDER BY, HAVING may be optional.
SELECT UNIQUE is an old syntax which was used in oracle description but later ANSI standard defines DISTINCT as the official
keyword.
After that oracle also added DISTINCT but did not withdraw the service of UNIQUE keyword for the sake of backward compatibility.
In simple words, we can say that SELECT UNIQUE statement is used to retrieve a unique or distinct element from the table.
1. SELECT UNIQUE column_name
2. FROM table_name;
SQL SELECT DISTINCT statement can also be used for the same cause.
In a table, there may be a chance to exist a duplicate value and sometimes we want to retrieve only unique values. In such scenarios,
SQL SELECT DISTINCT statement is used.
Note: SQL SELECT UNIQUE and SQL SELECT DISTINCT statements are same.
1. SELECT DISTINCT column_name ,column_name
2. FROM table_name;
1. SELECT DISTINCT home_town
2. FROM students
HOME_TOWN
Lucknow
Varanasi
The COUNT() function is used with SQL SELECT statement and it is very useful to count the number of rows in a table having
enormous data.
For example: If you have a record of the voters in selected area and want to count the number of voters then it is very difficult to do
it manually but you can do it easily by using the SQL SELECT COUNT query.
1. SELECT COUNT (expression)
2. FROM tables
3. WHERE conditions;
It will return the total number of names of employee_table. But null fields will not be counted.
The "select count(*) from table" is used to return the number of records in table.
SQL SELECT COUNT(DISTINCT column_name)
1. SELECT COUNT(DISTINCT name) FROM employee_table;
SQL SELECT AS
SQL AS is used to assign temporarily a new name to a table column.
It makes easy presentation of query results and allows the developer to label results more accurately without permanently renaming
table columns.
1. SELECT day_of_order AS "Date"
2. Customer As "Client",
3. Product,
4. Quantity,
5. FROM orders;
1. SELECT day_of_order AS "Date"
2. Customer As "Client",
3. Product,
4. Quantity,
5. FROM orders;
SQL SELECT IN
SQL IN is an operator used in a SQL query to help reduce the need to use multiple SQL "OR" conditions.
1. Expression IN (value 1, value 2 ... value n);
1. SELECT *
2. FROM students
3. WHERE students_name IN ( Amit , Raghav, Rajeev)
1. SELECT *
2. FROM marks
3. WHERE roll_no IN (001, 023, 024);
Let's see the example for the select from multiple tables:
1. SELECT orders.order_id, suppliers.name
2. FROM suppliers
3. INNER JOIN orders
4. ON suppliers.supplier_id = orders.supplier_id
5. ORDER BY order_id;
Let us take three tables, two tables of customers named customer1 and customer2 and the third table is product table.
Customer1 table
Cus_id Name1
1 Jack
2 Jill
Customer2 table
Cus_id Name2
1 Sandy
2 Venus
Product table
1 1 Laptop
2 2 Phone
3 P1 Pen
4 P2 Notebook
1. SELECT p. p_id, p.cus_id, p.p_name, c1.name1, c2.name2
2. FROM product AS p
3. LEFT JOIN customer1 AS c1
4. ON p.cus_id=c1.cus_id
5. LEFT JOIN customer2 AS c2
6. ON p.cus_id = c2.cus_id
For example: let's see the query to get all the records after '2013-12-12'.
1. SELECT * FROM
2. table-name WHERE your date-column >= '2013-12-12'
Let's see the another query to get all the records after '2013-12-12' and before '2013-12-13' date.
1. SELECT* FROM
2. table-name where your date-column < '2013-12-13' and your date-column >= '2013-12-12'
If you want to compare the dates within the query, you should use BETWEEN operator to compare the dates.
1. SELECT * FROM
2. table_name WHERE yourdate BETWEEN '2012-12-12' and '2013-12-12'
Or if you are looking for one date in particular you can use. You should change the date parameter into the acceptable form.
1. SELECT* FROM
2. table_name WHERE cast (datediff (day, 0, yourdate) as datetime) = '2012-12-12'
You can insert a row in the table by using SQL INSERT INTO command.
HTML Tutorial
In the first method there is no need to specify the column name where the data will be inserted, you need only their values.
1. INSERT INTO table_name
2. VALUES (value1, value2, value3....);
The second method specifies both the column name and values which you want to insert.
1. INSERT INTO table_name (column1, column2, column3....)
2. VALUES (value1, value2, value3.....);
Let's take an example of table which has five records within it.
1. INSERT INTO STUDENTS (ROLL_NO, NAME, AGE, CITY)
2. VALUES (1, ABHIRAM, 22, ALLAHABAD);
3. INSERT INTO STUDENTS (ROLL_NO, NAME, AGE, CITY)
4. VALUES (2, ALKA, 20, GHAZIABAD);
5. INSERT INTO STUDENTS (ROLL_NO, NAME, AGE, CITY)
6. VALUES (3, DISHA, 21, VARANASI);
7. INSERT INTO STUDENTS (ROLL_NO, NAME, AGE, CITY)
8. VALUES (4, ESHA, 21, DELHI);
9. INSERT INTO STUDENTS (ROLL_NO, NAME, AGE, CITY)
10. VALUES (5, MANMEET, 23, JALANDHAR);
1 ABHIRAM 22 ALLAHABAD
2 ALKA 20 GHAZIABAD
3 DISHA 21 VARANASI
4 ESHA 21 DELHI
5 MANMEET 23 JALANDHAR
You can create a record in CUSTOMERS table by using this syntax also.
1. INSERT INTO CUSTOMERS
2. VALUES (6, PRATIK, 24, KANPUR);
1 ABHIRAM 22 ALLAHABAD
2 ALKA 20 GHAZIABAD
3 DISHA 21 VARANASI
4 ESHA 21 DELHI
5 MANMEET 23 JALANDHAR
6 PRATIK 24 KANPUR
1. INSERT INTO table_name
2. [(column1, column2, .... column)]
3. SELECT column1, column2, .... Column N
4. FROM table_name [WHERE condition];
Note: when you add a new row, you should make sure that data type of the value and the column
should be matched.
If any integrity constraints are defined for the table, you must follow them.
1. CREATE TABLE student (ID INT VALUE VARCHAR (100));
1. INSERT INTO student (ID, NAME)
2. VALUES (1, 'ARMAAN');
3. INSERT INTO student (ID, NAME)
4. VALUES (2, 'BILLY');
5. INSERT INTO student (ID, NAME)
6. VALUES (3, 'CHARLIE');
TO CLEAN-UP:
1. TRUNCATE TABLE student;
1. INSERT INTO student (ID, NAME)
2. SELECT 1, 'ARMAAN'
3. UNION ALL
4. SELECT 2, 'BILLY'
5. UNION ALL
6. SELECT 3, 'CHARLIE';
7. TO CLEAN-UP:
8. TRUNCATE TABLE student;
1. INSERT INTO student (ID, NAME)
2. VALUES (1, 'ARMAAN'), (2, 'BILLY'), (3, 'CHARLIE');
3. TO CLEAN-UP:
4. DROP TABLE student;
Note:Row Constructor is a new feature for SQL Server 2008. It is not supported by SQL Server 2005.
SQL UPDATE
The SQL commands (UPDATE and DELETE) are used to modify the data that is already in the database. The SQL DELETE command
uses a WHERE clause.
SQL UPDATE statement is used to change the data of the records held by tables. Which rows is to be update, it is decided by a
condition. To specify condition, we use WHERE clause.
1. UPDATE table_name SET [column_name1= value1,... column_nameN = valueN] [WHERE condition]
1. UPDATE table_name
2. SET column_name = expression
3. WHERE conditions
Let's take an example: here we are going to update an entry in the source table.
SQL statement:
1. UPDATE students
2. SET User_Name = 'beinghuman'
3. WHERE Student_Id = '3'
Source Table:
If you are going to update multiple fields, you should separate each field assignment with a comma.
1. UPDATE students
2. SET User_Name = 'beserious', First_Name = 'Johnny'
3. WHERE Student_Id = '3'
1. UPDATE table_name
2. SET field1 = new-value1, field2 = new-value2,
3. [WHERE CLAUSE]
SYNTAX:
1. UPDATE tableDestination
2. SET tableDestination.col = value
3. WHERE EXISTS (
4. SELECT col2.value
5. FROM tblSource
6. WHERE tblSource.join_col = tblDestination. Join_col
7. AND tblSource.Constraint = value)
1. UPDATE
2. Table
3. SET
4. Table.column1 = othertable.column 1,
5. Table.column2 = othertable.column 2
6. FROM
7. Table
8. INNER JOIN
9. Other_table
10. ON
11. Table.id = other_table.id
My SQL SYNTAX:
If you want to UPDATE with SELECT in My SQL, you can use this syntax:
Cat_id, cat_name,
Rel_cat_id, rel_cat_name
We can update a single or multiple columns in SQL with SQL UPDATE query.
1. UPDATE students
2. SET student_id = 001
3. WHERE student_name = 'AJEET';
This SQL UPDATE example would update the student_id to '001' in the student table where student_name is 'AJEET'.
1. UPDATE students
2. SET student_name = 'AJEET',
3. Religion = 'HINDU'
4. WHERE student_name = 'RAJU';
This SQL UPDATE statement will change the student name to 'AJEET' and religion to 'HINDU' where the student name is 'RAJU'.
Let us take an example of a customer table. I have updated customer table that contains latest customer details from another source
system. I want to update the customer table with latest data. In such case, I will perform join between target table and source table
using join on customer ID.
1. UPDATE customer_table
2. INNER JOIN
3. Customer_table
4. ON customer_table.rel_cust_name = customer_table.cust_id
5. SET customer_table.rel_cust_name = customer_table.cust_name
Create table1
1. CREATE TABLE table1 (column1 INT, column2 INT, column3 VARCHAR (100))
2. INSERT INTO table1 (col1, col2, col3)
3. SELECT 1, 11, 'FIRST'
4. UNION ALL
5. SELECT 11,12, 'SECOND'
6. UNION ALL
7. SELECT 21, 13, 'THIRD'
8. UNION ALL
9. SELECT 31, 14, 'FOURTH'
Create table2
1. CREATE TABLE table2 (column1 INT, column2 INT, column3 VARCHAR (100))
2. INSERT INTO table2 (col1, col2, col3)
3. SELECT 1, 21, 'TWO-ONE'
4. UNION ALL
5. SELECT 11, 22, 'TWO-TWO'
6. UNION ALL
7. SELECT 21, 23, 'TWO-THREE'
8. UNION ALL
9. SELECT 31, 24, 'TWO-FOUR'
1. SELECT * FROM table_1
1. SELECT * FROM table_2
2 11 12 Second
3 21 13 Third
4 31 14 Fourth
1 1 21 Two-One
2 11 22 Two-Two
3 21 23 Two-Three
4 31 24 Two-Four
Our requirement is that we have table 2 which has two rows where Col 1 is 21 and 31. We want to update the value from table 2 to
table 1 for the rows where Col 1 is 21 and 31.
The most easiest and common way is to use join clause in the update statement and use multiple tables in the update statement.
1. UPDATE table 1
2. SET Col 2 = t2.Col2,
3. Col 3 = t2.Col3
4. FROM table1 t1
5. INNER JOIN table 2 t2 ON t1.Col1 = t2.col1
6. WHERE t1.Col1 IN (21,31)
1 1 11 First
2 11 12 Second
3 21 23 Two-Three
4 31 24 Two-Four
1 1 21 First
2 11 22 Second
3 21 23 Two-Three
4 31 24 Two-Four
Here we can see that using join clause in update statement. We have merged two tables by the use of
join clause.
If you want to update a date & time field in SQL, you should use the following query.
1. UPDATE table
2. SET Column_Name = 'YYYY-MM-DD HH:MM:SS'
3. WHERE Id = value
Firstly we take a table in which we want to update date and time fields.
If you want to change the first row which id is 1 then you should write the following syntax:
1. UPDATE table
2. SET EndDate = '2014-03-16 00:00:00.000'
3. WHERE Id = 1
<pNote: you should always remember that SQL must attach default 00:00:00.000 automatically.
This query will change the date and time field of the first row in that above assumed table.
</p
SQL DELETE
The SQL DELETE statement is used to delete rows from a table. Generally DELETE statement removes one or more records from a
table.
1. DELETE FROM table_name [WHERE condition];
Here table_name is the table which has to be deleted. The WHERE clause in SQL DELETE statement is optional here.
1. DELETE FROM EMPLOYEE WHERE ID=101;
1. DELETE FROM EMPLOYEE;
It will delete the all the records of EMPLOYEE table where ID is 101.
The WHERE clause in the SQL DELETE statement is optional and it identifies the rows in the column that gets deleted.
WHERE clause is used to prevent the deletion of all the rows in the table, If you don't use the WHERE clause you might loss all the
rows.
1. DELETE * FROM EMPLOYEE;
How to delete the table and what is the difference between DELETE and TRUNCATE statement?
How to use distinct keyword to delete all the duplicate rows from the table?
There is not used DELETE statement to delete the database. But, there is used DROP statement to delete the database.