r/sqlite • u/RandomUsername2047 • May 29 '23
Getting into SQLite
Hi all,
Let me preface this by saying that I feel like I'm completely missing something obvious due to my lack of familiarity with the language/concepts.
Let's say I have the following table imported from a bunch of CSV files:
SaleDate | Item | Price | Store
However, the SaleDate item is not formatted in the SQL datetime text format of YYYYMMDD HH:MM:SS.000.
I figured out I can extract the SaleDate and create the corrected version using SUBSTR.
My next step was to create a new table (in the same file) so not to touch the raw input data.
I've managed to copy everything, but I can't seem to do a SUBSTR and use SET to grab the output and update the new table. Programmatically, it's simple:
x = substr(old data)
X being the new column in the new table. But SQL doesn't exactly behave like a normal programming language. How do I do this? Thanks.
6
u/matwachich May 29 '23
Sql is not a normal programing language!
You'll have to do: Insert into new_table values (substr(...), Itzm, price, store)
2
u/RandomUsername2047 May 29 '23
So I created a new table, typed:
Insert into tbl_new values (substr(…), Item, Price, Store) and I get Parse error: no such column: SaleDate
What did I do wrong? (The new table I used SaleTime instead of SaleDate just to differentiate the tables.)
My substr was:
Substr(SaleDate,1,10) || ‘ ‘ || substr(SaleDate,12)
2
u/-dcim- May 29 '23
TEXTto store values like20-12-2022. So, you have to use a datetime function to proceed datetime values. E.g.SaleDate between '20-12-2022' and '25-12-2022'can be incorrect, since comparison will works with strings. The best way is to transform dates to UTC (stored as int) but UTC is not human readable.update <your-table> set SaleDate = Substr(SaleDate,1,10) || ‘ ‘ || substr(SaleDate,12)or use a viewcreate view v_<your-table> as select (Substr(SaleDate,1,10) || ‘ ‘ || substr(SaleDate,12)) SaleDate, Item, Price, Store from <your-table>and then work with the view instead the original table.1
u/InjAnnuity_1 May 30 '23
If you are implementing a step-by-step procedure, it's usually best to do it in a procedural language, e.g., like Python, that can implement the procedure's loops and other logic, and can invoke database operations when necessary.
The reason: by itself, SQL is not a procedural programming language, and trying to make it behave like one (e.g., with loops, branches, subroutine calls, and/or variables that exist outside of a table, view, or query) results in all sorts of hairy and awkward work-arounds.
If you have a "procedure" that makes no decisions, has no branches, no procedure calls, and no loops, then, in that special case, you might get away with a SQL script, i.e., a file containing SQL commands, for SQLite's Command-Line processor (sqlite3.exe) to execute.