Thursday, 3 January 2019

SQL Commands

1. CREATE
This command is used to create a table. The syntax of this command is:
create table tablename
(column1name datatype [constraint],
column2name datatype [constraint],
column3name datatype [constraint]);
create table citylist
(name varchar(20),
state varchar(20),
population number(8),
zipcode number(5) unique);
2. SELECT
The SELECT statement is used to select data from a database. The result is stored in a result table, called the
result-set.
Syntax:
SELECT [ALL | DISTINCT] columnname1 [,columnname2]
FROM tablename1 [,tablename2]
[WHERE condition] [ and|or condition...]
[GROUP BY column-list]
[HAVING "conditions]
[ORDER BY "column-list" [ASC | DESC] ]
The sections between the brackets [] are optional. A simpler syntax statement is:
select columnname1 [,columnname2] from tablename [where condition];




A "*" may be used to select all columns. The where clause is optional and only one column name must
be specified.
TheWhere Clause
This clause is used to specify which columns and values are returned. Where conditions specify an
OPERATOR to use for comparison. OPERATORs include:
  •  = - Equal
  •  < - Less than
  •  > - Greater than
  •  <= - Less than or equal
  •  >= - Greater than or equal
  •  <> - Not equal
  •  LIKE - Allows the wildcard operator, %, to be used to select items that are a partial match. An
example is:
select city, state from towntable where state LIKE 'north%';
This allows selection of all towns in states that begin with the word "north" allowing states like
North Dakota and North Carolina to be selected.
The GROUP BY Clause
This "GROUP BY" clause allows multiple columns to be grouped so aggregate functions (listed
below) may be performed on multiple columns with one command.
Aggregate function keywords:
  •  AVG - Get the average of a specified column.
  •  COUNT - Get the quantity of values in the column.
  •  MAX - Return the maximum value in a specified column.
  •  MIN - Return the minimum value in a specified column.
  •  SUM - Return the sum of all numeric values in the specified column.
Example:
SELECT MAX(population)
FROM citylist;
WHERE state = 'Indiana';
Example using the GROUP BY clause which gets the smallest population of each city in every state:
SELECT MIN(population)
FROM citylist;
GROUP BY state;
The HAVING Clause
Allows selection of set test criteria on rows. You can display average size of towns whose population is less
than 100.


The ORDER BY Clause
This clause lets results be displayed in ascending or descending order. Keywords:
  •  ASC - Ascending order.
  •  DESC - Descending order.
  • Other Keywords
  •  ALL - Used to select all records.
  •  DISTINCT - Used to select unique records. Only unique values are returned.
  • Example:- SELECT city, state FROM towntable WHERE population > '100000';
3. INSERT
The insert statement is used to insert a new row in a table. This statement is used to insert a row of data in a
table. All inserted values are enclosed using single quote strings. The syntax of this command is:
insert into tablename
(column1name,column2name...columnxname)
values (value1,value2...valuex);
Example
insert into citylist
(name, state, population, zipcode)
values ('Argos', 'Indiana', '89', '46501');
or
insert into citylist
values ('Argos', 'Indiana', '89', '46501');
4. UPDATE
The UPDATE statement is used to update existing records in a table. This command is used to make
changes to records in tables. Syntax:
update tablename
set columnname = newvalue [,columnxname = newvaluex...]
where columnname OPERATOR value [and|or columnnamex OPERATOR valuex];
The OPERATOR is one of the conditions listed on the Select Command page.
OPERATORs include:
  •  = - Equal
  •  < - Less than
  •  > - Greater than
  •  <= - Less than or equal
  •  >= - Greater than or equal
  •  <> - Not equal
  •  LIKE - Allows the wildcard operator, %, to be used to select items that are a partial match. An
  • example is:
select city, state from towntable where state like 'north%'
This allows selection of all towns in states that begin with the word "north" allowing states like
North Dakota and North Carolina to be selected.


Example
update citylist
set population = population+1
where name = 'Argos' and
state = 'Indiana';
5. DELETE
The DELETE statement is used to delete rows in a table. This command is used to delete rows or records in
a table. The syntax of this command is:
delete from "tablename"
where columnname OPERATOR value [and|or
columnnamex OPERATOR valuex];
Without the where clause, all records in the table will be deleted.
Example
delete from citylist
where name = 'Argos' and state = 'Indiana';
6. DROP
The DROP TABLE statement is used to delete a table. The DROP DATABASE statement is used to delete
a database. Used to remove an entire table from the database. Syntax:
drop table tablename
Example
drop table citylist;
7. ALTER
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. To add a
column in a table, use the following syntax:
ALTER TABLE table_name
ADD column_name datatype;
To delete a column in a table, use the following syntax
ALTER TABLE table_name
DROP COLUMN column_name;
To change the data type of a column in a table, use the following syntax:
ALTER TABLE table_name
ALTER COLUMN column_name datatype
8. RENAME
We can rename any table by using RENAME sql command. The data will not be lost. Only the table name
will be changed to new name. Here is the command to change the name of a table.
Syntax :- RENAME Source table name to destination table name;
Example:- rename emp to employee;

Features/ Advantages of SQL

  •  Stored Procedures
The one main advantage of using SQL is the use of stored procedures. Stored procedures are lines of code
that are called by the application. They are placed on the server, and they are pre-compiled for quicker
response times. Stored procedures require the knowledge of SQL Server syntax, which is called T-SQL
(transaction SQL). The use of stored procedures also centralizes code, so troubleshooting bad database
requests can be observed by a database administrator.
  •  Scalability
The term scalability is used to describe the ability to grow when the business becomes bigger. When
businesses grow quickly, a small database application like Access can be a bottleneck for a website or
desktop software. Microsoft SQL Server is quick for large and small businesses, so as the business grows,
the SQL Server can handle the new volume of database requests. SQL Server can handle millions of records
and transactions.
  •  Security

Security is a major issue for any site. SQL Server allows the administrator to grant access or deny access for
users. The SQL Server has a specific section of the application where users are added to the permissions.
SQL Server allows administrators to specify which tables and stored procedures users are able to access and
query. This limits what records and user information can be queried, which protects the business's customer
information.
  • Transaction Logs
Transaction logs are objects on the SQL Server that record the retrieval, update and deletion of records.
There are two reasons to keep transaction logs. The first is for rollback procedures. This process is used for
accidental updates or deletions. The administrator can return records back to the original data by using
transaction logs. Secondly, the transaction logs can be used for security purposes. If the administrator
suspects a breach of security, he can watch the transaction logs for any type of data retrieval and identify the
severity of the breach.
  • Automatic Backup

SQL Server has an automatic backup option. The SQL Server automatically saves a copy of the database
and the transaction logs on another hard drive or media like a CD-ROM or a DVD. Small applications like
Access do not have this option, and backups are an integral part of disaster recovery. SQL Server also has
procedures that allow the administrator to quickly restore a database when data is lost or corrupted, or the
server has a hard drive crash.

Introduction of SQL

Structured Query Language (SQL) is a specialized language for updating, deleting, and requesting
information from databases. SQL is an ANSI and ISO standard, and is the de facto standard database query
language. A variety of established database products support SQL, including products from Oracle and
Microsoft SQL Server. It is widely used in both industry and academia, often for enormous, complex
databases.
In a distributed database system, a program often referred to as the database's "back end" runs constantly on
a server, interpreting data files on the server as a standard relational database. Programs on client computers
allow users to manipulate that data, using tables, columns, rows, and fields. To do this, client programs send
SQL statements to the server. The server then processes these statements and returns replies to the client
program.
SQL is a standardized query language for requesting information from a database. The original version
called SEQUEL (structured English query language) was designed by an IBM research center in 1974 and
1975. SQL was first introduced as a commercial database system in 1979 by Oracle Corporation.
Historically, SQL has been the favorite query language for database management systems running
on minicomputers and mainframes. Increasingly, however, SQL is being supported by PC database systems
because it supports distributed databases (databases that are spread out over several computer systems). This
enables several users on a local-area network to access the same database simultaneously.
 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
The most common operation in SQL is the query, which is performed with the
declarative SELECT statement. SELECT retrieves data from one or more tables, or expressions. Standard
SELECT statements have no persistent effects on the database. Some non-standard implementations
of SELECT can have persistent effects, such as the SELECT INTO syntax that exists in some databases.
Queries allow the user to describe desired data, leaving the database management system
(DBMS) responsible for planning, optimizing, and performing the physical operations necessary to produce
that result as it chooses. A query includes a list of columns to be included in the final result immediately
following the SELECT keyword. An asterisk ("*") can also be used to specify that the query should return
all columns of the queried tables. SELECT is the most complex statement in SQL, with optional keywords
and clauses that include:
 The FROM clause which indicates the table(s) from which data is to be retrieved. The FROM clause can
include optional JOIN sub clauses to specify the rules for joining tables.
 The WHERE clause includes a comparison predicate, which restricts the rows returned by the query.
The WHERE clause eliminates all rows from the result set for which the comparison predicate does not
evaluate to True.
 The GROUP BY clause is used to project rows having common values into a smaller set of
rows. GROUP BY is often used in conjunction with SQL aggregation functions or to eliminate duplicate
rows from a result set. The WHERE clause is applied before the GROUP BY clause.
 The HAVING clause includes a predicate used to filter rows resulting from the GROUP BY clause.
Because it acts on the results of the GROUP BY clause, aggregation functions can be used in
the HAVING clause predicate.
 The ORDER BY clause identifies which columns are used to sort the resulting data, and in which
direction they should be sorted (options are ascending or descending). Without an ORDER BY clause,
the order of rows returned by an SQL query is undefined.

What is Menu?

Windows applications provide groups of related commands in Menus. These commands depends on the
application, but some-such as Open and Save are frequently found in applications. Menus are intrinsic
controls. On the other hand, menus behave differently from other controls. For example, you don't drop menu
items on a form from the Toolbox; rather, you design them in the Menu Editor window, as you can see in the
figur below.
An expanded Menu Editor window.
You


You invoke this tool from the Menu Editor button on the standard toolbar or by pressing the Ctrl+E shortcut
key. There's also a Menu Editor command in the Tools menu, but you probably won't use it often. Visual
Basic provides an easy way to create menus with the modal Menu Editor dialog. The below dialog is
displayed when the Menu Editor is selected in the Tool Menu. The Menu Editor command is grayed unless
the form is visible. And also you can display the Menu Editor window by right clicking on the Form and
selecting Menu Editor.
Basically, each menu item has a Caption property (possibly with an embedded & character to create an
access key) and a Name. Each item also exposes three Boolean properties, Enabled, Visible, and Checked,
which you can set both at design time and at run time. At design time, you can assign the menu item a
shortcut key so that your end users don't have to go through the menu system each time they want to execute a
frequent command. The assigned shortcut key can't be queried at run time, much less modified.
Building a menu is a simple, albeit more tedious, job: You enter the item's Caption and Name, set other
properties (or accept the default values for those properties), and press Enter to move to the next item. When
you want to create a submenu, you press the Right Arrow button (or the Alt+R hot key). When you want to
return to work on top-level menus—those items that appear in the menu bar when the application runs—you
click the Left Arrow button (or press Alt+L). You can move items up and down in the hierarchy by clicking
the corresponding buttons or the hot keys Alt+U and Alt+B, respectively.
You can create up to five levels of submenus (six including the menu bar), which are too many even for the
most patient user. If you find yourself working with more than three menu levels, think about trashing your
specifications and redesigning your application from the ground up.
You can insert a separator bar using the hypen (-) character for the Caption property. But even these separator
items must be assigned a unique value for the Name property, which is a real nuisance. If you forget to enter a
menu item's Name, the Menu Editor complains when you decide to close it. The convention used in this book
is that all menu names begin with the three letters menu.
One of the most annoying defects of the Menu Editor tool is that it doesn't permit you to reuse the menus you
have already written in other applications. It would be great if you could open another instance of the Visual
Basic IDE, copy one or more menu items to the clipboard, and then paste those menu items in the application
under development.
You can do that with controls and with pieces of code, but not with menus! The best thing you can do in
Visual Basic is load the FRM file using an editor such as Notepad, find the portion in the file that corresponds
to the menu you're interested in, load the FRM file you're developing (still in Notepad), and paste the code
there. This isn't the easiest operation, and it's also moderately dangerous: If you paste the menu definition in
the wrong place, you could make your FRM form completely unreadable. Therefore, always remember to
make backup copies of your forms before trying this operation.
Better news is that you can add a finished menu to a form in your application with just a few mouse clicks. All
you have to do is activate the Add-In Manager from the Add-Ins menu, choose the VB 6 Template Manager,
and tick the Loaded/Unloaded check box. After you do that, you'll find three new commands in the Tools
menu: Add Code Snippet, Add Menu, and Add Control Set. Visual Basic 6 comes with a few menu templates,
as you can see in the following figure, that you might find useful as a starting point for building your own
templates.
To create your menu templates, you only have to create a form with the complete menu and all the related
code and then store this form in the \Templates\Menus directory. (The complete path, typically c:\Program
Files\Microsoft Visual Studio\VB98\Template, can be found in the Environment tab of the Options dialog box
on the Tools menu. The Template Manager was already available with Visual Basic 5, but it had to be
installed manually and relatively few programmers were aware of its existence.
The Template Manager in action
The programmer can create menu control arrays. The Index TextBox specifies the menu's index in the control
array. The Menu Editor dialog also provides several CheckBoxes to control the appearance of the Menu.

Checked : This is unchecked by default and allows the programmer the option of creating a checked menu
item( a menu item that act as a toggle and displays a check mark when selected. The following is a Check
Menu items.
Enabled : specifies whether a menu is disabled or not. If you see a disabled command in a menu that means
that feature is not available. The Visible checkbox specifies whether the menu is visible or not.
To add commands to the Form's menu bar, enter a caption and a name for each command. As soon as you
start typing the command's caption, it also appears in a new line in the list at the bottom of the Menu Editor
window. To add more commands click Enter and type the Caption and the Name.
Creating Menus
Open a new Project and save the form as menu.frm and save the project as menu.vbp. Choose Tools ››› Menu
Editor and type the menu items as shown below.
Caption Name Caption Name
File mnuFile Edit mnuEdit
Open mnuOpen Copy mnuCopy
Save mnuSave Cut mnuCut
Exit mnuExit Paste mnuPaste

How Big MySQL Tables Can Be


MySQL 3.22 had a 4GB (4 gigabyte) limit on table size. With the MyISAM storage engine in MySQL 3.23, the maximum table size was increased to 8 million terabytes (2 ^ 63 bytes). With this larger allowed table size, the maximum effective table size for MySQL databases is usually determined by operating system constraints on file sizes, not by MySQL internal limits.
The InnoDB storage engine maintains InnoDB tables within a tablespace that can be created from several files. This allows a table to exceed the maximum individual file size. The tablespace can include raw disk partitions, which allows extremely large tables. The maximum tablespace size is 64TB.
The following table lists some examples of operating system file-size limits. This is only a rough guide and is not intended to be definitive. For the most up-to-date information, be sure to check the documentation specific to your operating system.
Operating System
File-size Limit
Linux 2.2-Intel 32-bit
2GB (LFS: 4GB)
Linux 2.4
(using ext3 filesystem) 4TB
Solaris 9/10
16TB
NetWare w/NSS filesystem
8TB
win32 w/ FAT/FAT32
2GB/4GB
win32 w/ NTFS
2TB (possibly larger)
MacOS X w/ HFS+
2TB
On Linux 2.2, you can get MyISAM tables larger than 2GB in size by using the Large File Support (LFS) patch for the ext2 filesystem. On Linux 2.4, patches also exist for ReiserFS to get support for big files (up to 2TB). Most current Linux distributions are based on kernel 2.4 and include all the required LFS patches. With JFS and XFS, petabyte and larger files are possible on Linux. However, the maximum available file size still depends on several factors, one of them being the filesystem used to store MySQL tables.
For a detailed overview about LFS in Linux, have a look at Andreas Jaeger's Large File Support in Linux page at http://www.suse.de/~aj/linux_lfs.html.
Windows users please note: FAT and VFAT (FAT32) are not considered suitable for production use with MySQL. Use NTFS instead.
By default, MySQL creates MyISAM tables with an internal structure that allows a maximum size of about 4GB. You can check the maximum table size for a table with the SHOW TABLE STATUS statement or with myisamchk -dv tbl_name. See Section 13.5.4, “SHOW Syntax”.
If you need a MyISAM table that is larger than 4GB in size (and your operating system supports large files), the CREATE TABLE statement allows AVG_ROW_LENGTH and MAX_ROWS options. See Section 13.2.6, “CREATE TABLE Syntax”. You can also change these options with ALTER TABLE after the table has been created, to increase the table's maximum allowable size. See Section 13.2.2, “ALTER TABLE Syntax”.
Other ways to work around file-size limits for MyISAM tables are as follows:
·        If your large table is read-only, you can use myisampack to compress it. myisampack usually compresses a table by at least 50%, so you can have, in effect, much bigger tables. myisampack also can merge multiple tables into a single table. See Section 8.2, “myisampack, the MySQL Compressed Read-only Table Generator”.
·        Another way to get around the operating system file limit for MyISAM data files is by using the RAID options. See Section 13.2.6, “CREATE TABLE Syntax”.
·        MySQL includes a MERGE library that allows you to handle a collection of MyISAM tables that have identical structure as a single MERGE table. See Section 14.2, “The MERGE Storage Engine”.

 


13.2.4. CREATE DATABASE Syntax

CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
    [create_specification [, create_specification] ...]
create_specification:
    [DEFAULT] CHARACTER SET charset_name
  | [DEFAULT] COLLATE collation_name
CREATE DATABASE creates a database with the given name. To use CREATE DATABASE, you need the CREATE privilege on the database.
Rules for allowable database names are given in Section 9.2, “Database, Table, Index, Column, and Alias Names”. An error occurs if the database exists and you didn't specify IF NOT EXISTS.
As of MySQL 4.1.1, create_specification options can be given to specify database characteristics. Database characteristics are stored in the db.opt file in the database directory. The CHARACTER SET clause specifies the default database character set. The COLLATE clause specifies the default database collation. Character set and collation names are discussed in Chapter 10, Character Set Support.
Databases in MySQL are implemented as directories containing files that correspond to tables in the database. Because there are no tables in a database when it is initially created, the CREATE DATABASE statement only creates a directory under the MySQL data directory (and the db.opt file, for MySQL 4.1.1 and up).
If you manually create a directory under the data directory (for example, with mkdir), the server considers it a database directory and it shows up in the output of SHOW DATABASES.
CREATE SCHEMA can be used as of MySQL 5.0.2.
You can also use the mysqladmin program to create databases. See Section 8.4, “mysqladmin, Administering a MySQL Server”.

13.2.8. DROP DATABASE Syntax

DROP {DATABASE | SCHEMA} [IF EXISTS] db_name
DROP DATABASE drops all tables in the database and deletes the database. Be very careful with this statement! To use DROP DATABASE, you need the DROP privilege on the database.
In MySQL 3.22 or later, you can use the keywords IF EXISTS to prevent an error from occurring if the database doesn't exist.
DROP SCHEMA can be used as of MySQL 5.0.2.
If you use DROP DATABASE on a symbolically linked database, both the link and the original database are deleted.
As of MySQL 4.1.2, DROP DATABASE returns the number of tables that were removed. This corresponds to the number of .frm files removed.
The DROP DATABASE statement removes from the given database directory those files and directories that MySQL itself may create during normal operation:
·        All files with these extensions:
.BAK
.DAT
.HSH
.ISD
.ISM
.ISM
.MRG
.MYD
.MYI
.db
.frm

·        All subdirectories with names that consist of two hex digits 00-ff. These are subdirectories used for RAID tables.
·        The db.opt file, if it exists.
If other files or directories remain in the database directory after MySQL removes those just listed, the database directory cannot be removed. In this case, you must remove any remaining files or directories manually and issue the DROP DATABASE statement again.
You can also drop databases with mysqladmin. See Section 8.4, “mysqladmin, Administering a MySQL Server”.