These are some notes on SQL a language for creating and querying databases, I’m learning it because a couple of programming projects I have in mind for work and home will need it. The source for these notes is Head First SQL book. I’ve used a previous book in this series and I quite like the presentational style. I’m using MySQL via it’s command line client to do the exercises, because it’s about as straightforward as you can get. The code is formatted for display using this SQL to HTML formatter. Notepad++ recognises SQL as a language and will do syntax highlighting, so I type my commands into it and copy them into the MySQL command line client.
SQL is quite an old language and the convention is to write keywords in block capitals (reminds me of FORTRAN!). Command sequences are terminated by a semi-colon.
To start, this sequence creates a database, sets it as active and then adds a table containing a range of fields of different types, the command DESC shows the layout of a table:
CREATE DATABASE my_database;
CREATE TABLE contacts
contact_id INT NOT NULL,
weight DEC(3, 2) NOT NULL DEFAULT 80.00,
NOT NULL keywords are used if a field must be specified on INSERT. Once created data can be added to the table using the INSERT command:
INSERT INTO contacts (contact_id,first_name,last_name,birthday,life_story,weight,appointment)
(1,‘Ian’,‘Hopkinson’,‘1970-24-04’,‘A very long text string’,80.0,
INSERT can be used with no specified fields (in which case values for all supplied fields must be provided for all fields), or with a subset of fields. In order to add the ‘ character we can either use ” or \’ (where ” is two single quote characters, rather than a double quote).
To delete a table:
This command should be used with care since it deletes the table whether or not it contains data. The next post should be on the SELECT command.
Of course you can find SQL cheatsheets elsewhere.
Keywords: CREATE, DATABASE, TABLE, USE, DESC, DROP, INSERT INTO, VALUES, INT, VARCHAR, BLOB, CHAR, DATETIME, DATE, DEC