14 Oct 2010
Web frameworks that come with database abstraction layers like ActiveRecord have given us a degree of freedom in the database software we use. Database portability increases the number of platforms on which we can deploy our apps, but you still need to know how to use the different databases. For those of you who are used to MySQL or PostgreSQL and need to learn SQLite (or some other combination of those), here are some rough command equivalents in each to get you started.
Some of these commands are given at your operating system command prompt and others are given at the database client command prompt. I have indicated the prompt in each command below: $ is your OS, and db> is your database client.
$ sqlite <db file>
$ mysql -u<user> -p <db name>
$ psql -U <user> <db name>
Databases are stored in separate files, usually with a .sqlite3 or .db extension. SQLite cannot find these files for you.
db> SHOW DATABASES;
db> SELECT datname FROM pg_database;
$ sqlite3 <db file>
$ mysqladmin -u<user> -p create <db name>
$ createdb <db name>
Close the client and re-open with another file.
db> USE <db name>
db> \connect <db name>
db> .schema
db> SHOW tables;
db> \dt
db> .schema <table>
db> DESCRIBE <table>;
db> \d <table>
Where there is more than one way to accomplish the same thing I have chosen the most generally-usable functions since that is normally what you’ll want to use for cross-database compatibility. There are some common things which SQLite cannot do out of the box, but a lot of useful functions can be added with the extension-functions. Compilation instructions are in the downloaded file. Load the extension at the SQLite prompt:
.load <compiled extension filename>
SQLite, MySQL, and PostgreSQL
SUBSTR(<string>, <start>, <length>) # length argument is optional
CHARINDEX(<sta>, <haystack>) # requires extension-functions
MySQL, and PostgreSQL
POSITION(<sta> IN <haystack>)
SQLite, MySQL, and PostgreSQL
POWER(<base>, <exponent>) # requires extension-functions in SQLite
STRFTIME("%Y", <date>)
YEAR(<date>)
EXTRACT(YEAR FROM <date>)
MySQL provides an IF() function that many people are used to:
IF(<condition>, <then-expression>, <else-expression>)
This is convenient but not supported by other databases. It’s better to use the more widely-implemented CASE statement:
SQLite, MySQL, and PostgreSQL
CASE WHEN <condition> THEN <expression> ELSE <expression> END
This is commonly achieved in MySQL through the use of IFNULL(x, y), but the COALESCE function is equivalent in the case of two arguments, more general, and more widely implemented. It takes any number of arguments and returns the first one which is not null.
SQLite, MySQL, and PostgreSQL
COALESCE(<value1>, <value2>, ...)
That’s all for now, though I will probably add to this list in the future. If there is anything you would like to see added, please let me know.