Debian Codegraph @

www/datatype3.html

raw
1 <!DOCTYPE html>
2 <html><head>
3 <meta name="viewport" content="width=device-width, initial-scale=1.0">
4 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
5 <link href="sqlite.css" rel="stylesheet">
6 <title>Datatypes In SQLite</title>
7 <!-- path= -->
8 </head>
9 <body>
10 <div class=nosearch>
11 <a href="index.html">
12 <img class="logo" src="images/sqlite370_banner.gif" alt="SQLite" border="0">
13 </a>
14 <div><!-- IE hack to prevent disappearing logo --></div>
15 <div class="tagline desktoponly">
16 Small. Fast. Reliable.<br>Choose any three.
17 </div>
18 <div class="menu mainmenu">
19 <ul>
20 <li><a href="index.html">Home</a>
21 <li class='mobileonly'><a href="javascript:void(0)" onclick='toggle_div("submenu")'>Menu</a>
22 <li class='wideonly'><a href='about.html'>About</a>
23 <li class='desktoponly'><a href="docs.html">Documentation</a>
24 <li class='desktoponly'><a href="download.html">Download</a>
25 <li class='wideonly'><a href='copyright.html'>License</a>
26 <li class='desktoponly'><a href="support.html">Support</a>
27 <li class='desktoponly'><a href="prosupport.html">Purchase</a>
28 <li class='search' id='search_menubutton'>
29 <a href="javascript:void(0)" onclick='toggle_search()'>Search</a>
30 </ul>
31 </div>
32 <div class="menu submenu" id="submenu">
33 <ul>
34 <li><a href='about.html'>About</a>
35 <li><a href='docs.html'>Documentation</a>
36 <li><a href='download.html'>Download</a>
37 <li><a href='support.html'>Support</a>
38 <li><a href='prosupport.html'>Purchase</a>
39 </ul>
40 </div>
41 <div class="searchmenu" id="searchmenu">
42 <form method="GET" action="search">
43 <select name="s" id="searchtype">
44 <option value="d">Search Documentation</option>
45 <option value="c">Search Changelog</option>
46 </select>
47 <input type="text" name="q" id="searchbox" value="">
48 <input type="submit" value="Go">
49 </form>
50 </div>
51 </div>
52 <script>
53 function toggle_div(nm) {
54 var w = document.getElementById(nm);
55 if( w.style.display=="block" ){
56 w.style.display = "none";
57 }else{
58 w.style.display = "block";
59 }
60 }
61 function toggle_search() {
62 var w = document.getElementById("searchmenu");
63 if( w.style.display=="block" ){
64 w.style.display = "none";
65 } else {
66 w.style.display = "block";
67 setTimeout(function(){
68 document.getElementById("searchbox").focus()
69 }, 30);
70 }
71 }
72 function div_off(nm){document.getElementById(nm).style.display="none";}
73 window.onbeforeunload = function(e){div_off("submenu");}
74 /* Disable the Search feature if we are not operating from CGI, since */
75 /* Search is accomplished using CGI and will not work without it. */
76 if( !location.origin || !location.origin.match || !location.origin.match(/http/) ){
77 document.getElementById("search_menubutton").style.display = "none";
78 }
79 /* Used by the Hide/Show button beside syntax diagrams, to toggle the */
80 function hideorshow(btn,obj){
81 var x = document.getElementById(obj);
82 var b = document.getElementById(btn);
83 if( x.style.display!='none' ){
84 x.style.display = 'none';
85 b.innerHTML='show';
86 }else{
87 x.style.display = '';
88 b.innerHTML='hide';
89 }
90 return false;
91 }
92 var antiRobot = 0;
93 function antiRobotGo(){
94 if( antiRobot!=3 ) return;
95 antiRobot = 7;
96 var j = document.getElementById("mtimelink");
97 if(j && j.hasAttribute("data-href")) j.href=j.getAttribute("data-href");
98 }
99 function antiRobotDefense(){
100 document.body.onmousedown=function(){
101 antiRobot |= 2;
102 antiRobotGo();
103 document.body.onmousedown=null;
104 }
105 document.body.onmousemove=function(){
106 antiRobot |= 2;
107 antiRobotGo();
108 document.body.onmousemove=null;
109 }
110 setTimeout(function(){
111 antiRobot |= 1;
112 antiRobotGo();
113 }, 100)
114 antiRobotGo();
115 }
116 antiRobotDefense();
117 </script>
118 <div class=fancy>
119 <div class=nosearch>
120 <div class="fancy_title">
121 Datatypes In SQLite
122 </div>
123 <div class="fancy_toc">
124 <a onclick="toggle_toc()">
125 <span class="fancy_toc_mark" id="toc_mk">&#x25ba;</span>
126 Table Of Contents
127 </a>
128 <div id="toc_sub"><div class="fancy-toc1"><a href="#datatypes_in_sqlite">1. Datatypes In SQLite</a></div>
129 <div class="fancy-toc1"><a href="#storage_classes_and_datatypes">2. Storage Classes and Datatypes</a></div>
130 <div class="fancy-toc2"><a href="#boolean_datatype">2.1. Boolean Datatype</a></div>
131 <div class="fancy-toc2"><a href="#date_and_time_datatype">2.2. Date and Time Datatype</a></div>
132 <div class="fancy-toc1"><a href="#type_affinity">3. Type Affinity</a></div>
133 <div class="fancy-toc2"><a href="#determination_of_column_affinity">3.1. Determination Of Column Affinity</a></div>
134 <div class="fancy-toc3"><a href="#affinity_name_examples">3.1.1. Affinity Name Examples</a></div>
135 <div class="fancy-toc2"><a href="#affinity_of_expressions">3.2. Affinity Of Expressions</a></div>
136 <div class="fancy-toc2"><a href="#column_affinity_for_views_and_subqueries">3.3. Column Affinity For Views And Subqueries</a></div>
137 <div class="fancy-toc3"><a href="#column_affinity_for_compound_views">3.3.1. Column Affinity For Compound Views</a></div>
138 <div class="fancy-toc2"><a href="#column_affinity_behavior_example">3.4. Column Affinity Behavior Example</a></div>
139 <div class="fancy-toc1"><a href="#comparison_expressions">4. Comparison Expressions</a></div>
140 <div class="fancy-toc2"><a href="#sort_order">4.1. Sort Order</a></div>
141 <div class="fancy-toc2"><a href="#type_conversions_prior_to_comparison">4.2. Type Conversions Prior To Comparison</a></div>
142 <div class="fancy-toc2"><a href="#comparison_example">4.3. Comparison Example</a></div>
143 <div class="fancy-toc1"><a href="#operators">5. Operators</a></div>
144 <div class="fancy-toc1"><a href="#sorting_grouping_and_compound_selects">6. Sorting, Grouping and Compound SELECTs</a></div>
145 <div class="fancy-toc1"><a href="#collating_sequences">7. Collating Sequences</a></div>
146 <div class="fancy-toc2"><a href="#assigning_collating_sequences_from_sql">7.1. Assigning Collating Sequences from SQL</a></div>
147 <div class="fancy-toc2"><a href="#collation_sequence_examples">7.2. Collation Sequence Examples</a></div>
148 </div>
149 </div>
150 <script>
151 function toggle_toc(){
152 var sub = document.getElementById("toc_sub")
153 var mk = document.getElementById("toc_mk")
154 if( sub.style.display!="block" ){
155 sub.style.display = "block";
156 mk.innerHTML = "&#x25bc;";
157 } else {
158 sub.style.display = "none";
159 mk.innerHTML = "&#x25ba;";
160 }
161 }
162 </script>
163 </div>
164
165
166
167
168
169 <h1 id="datatypes_in_sqlite"><span>1. </span>Datatypes In SQLite</h1>
170 <p>Most SQL database engines (every SQL database engine other than SQLite,
171 as far as we know) uses static, rigid typing. With static typing, the datatype
172 of a value is determined by its container - the particular column in
173 which the value is stored.</p>
174
175 <p>SQLite uses a more general dynamic type system. In SQLite, the datatype
176 of a value is associated with the value itself, not with its container.
177 The dynamic type system of SQLite is backwards
178 compatible with the more common static type systems of other database engines
179 in the sense that SQL statements that work on statically typed databases
180 work the same way in SQLite. However, the dynamic typing in SQLite allows
181 it to do things which are not possible in traditional rigidly typed
182 databases. <a href="flextypegood.html">Flexible typing is a feature</a> of SQLite, not a bug.</p>
183
184 <p>Update:
185 As of version 3.37.0 (2021-11-27), SQLite provides <a href="stricttables.html">STRICT tables</a>
186 that do rigid type enforcement, for developers who prefer that kind of thing.
187
188 <a name="storageclasses"></a>
189
190 </p><h1 id="storage_classes_and_datatypes"><span>2. </span>Storage Classes and Datatypes</h1>
191
192 <p>Each value stored in an SQLite database (or manipulated by the
193 database engine) has one of the following storage classes:</p>
194 <ul>
195 <li><p><b>NULL</b>.
196 The value is a NULL value.</p>
197
198 </li><li><p><b>INTEGER</b>. The value is a signed integer, stored in 0, 1,
199 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.</p>
200
201 </li><li><p><b>REAL</b>. The value is a floating point value, stored as
202 an 8-byte IEEE floating point number.</p>
203
204 </li><li><p><b>TEXT</b>. The value is a text string, stored using the
205 database encoding (UTF-8, UTF-16BE or UTF-16LE).</p>
206
207 </li><li><p><b>BLOB</b>. The value is a blob of data, stored exactly as
208 it was input.</p>
209 </li></ul>
210
211 <p>A storage class is more general than a datatype.
212 The INTEGER storage class, for example, includes 7 different integer
213 datatypes of different lengths.
214 <a href="fileformat2.html#record_format">This makes a difference on disk.</a>
215 But as soon as INTEGER values are read off of disk and into memory for
216 processing, they are converted to the most general datatype
217 (8-byte signed integer).
218 And so for the most part, "storage class" is indistinguishable from
219 "datatype" and the two terms can be used interchangeably.</p>
220
221 <p>Any column in an SQLite version 3 database,
222 except an <a href="lang_createtable.html#rowid">INTEGER PRIMARY KEY</a> column, may be used to store a value
223 of any storage class.</p>
224
225 <p>All values in SQL statements, whether they are literals embedded in SQL
226 statement text or <a href="lang_expr.html#varparam">parameters</a> bound to
227 <a href="c3ref/stmt.html">precompiled SQL statements</a>
228 have an implicit storage class.
229 Under circumstances described below, the
230 database engine may convert values between numeric storage classes
231 (INTEGER and REAL) and TEXT during query execution.
232 </p>
233
234 <a name="boolean"></a>
235
236 <h2 id="boolean_datatype"><span>2.1. </span>Boolean Datatype</h2>
237
238 <p>SQLite does not have a separate Boolean storage class.
239 Instead, Boolean values are stored as integers 0 (false) and 1 (true).</p>
240
241 <p>SQLite recognizes the keywords "TRUE" and "FALSE",
242 as of version 3.23.0 (2018-04-02) but those keywords are
243 really just alternative spellings for the integer literals 1 and 0
244 respectively.
245
246 <a name="datetime"></a>
247
248 </p><h2 id="date_and_time_datatype"><span>2.2. </span>Date and Time Datatype</h2>
249
250 <p>SQLite does not have a storage class set aside for storing
251 dates and/or times.
252 Instead, the built-in <a href="lang_datefunc.html">Date And Time Functions</a> of SQLite are capable of
253 storing dates and times as TEXT, REAL, or INTEGER values:</p>
254
255 <ul>
256 <li><b>TEXT</b> as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
257 </li><li><b>REAL</b> as Julian day numbers, the number of days since
258 noon in Greenwich on November 24, 4714 B.C. according to the
259 proleptic Gregorian calendar.
260 </li><li><b>INTEGER</b> as Unix Time, the number of seconds since
261 1970-01-01 00:00:00 UTC.
262 </li></ul>
263
264 <p>Applications can choose to store dates and times in any of these
265 formats and freely convert between formats using the built-in
266 <a href="lang_datefunc.html">date and time functions</a>.</p>
267
268
269 <a name="affinity"></a>
270
271 <h1 id="type_affinity"><span>3. </span>Type Affinity</h1>
272
273 <p>
274 SQL database engines that use rigid typing will usually try to
275 automatically convert values to the appropriate datatype. Consider this:
276
277 </p><blockquote><pre>
278 CREATE TABLE t1(a INT, b VARCHAR(10));
279 INSERT INTO t1(a,b) VALUES('123',456);
280 </pre></blockquote>
281
282 <p>
283 Rigidly-typed database will convert the string '123' into an
284 integer 123 and the integer 456 into a string '456' prior to
285 doing the insert.
286
287 </p><p>
288 In order to maximize compatibility between SQLite and other database
289 engines, and so that the example above will work on SQLite as it does
290 on other SQL database engines,
291 SQLite supports the concept of "type affinity" on columns.
292 The type affinity of a column is the recommended type for data stored
293 in that column. The important idea here is that the type is recommended, not
294 required. Any column can still store any type of data.
295 It is just that some columns, given the choice, will prefer to use
296 one storage class over another. The preferred storage class for
297 a column is called its "affinity".
298 </p>
299
300 <p>Each column in an SQLite 3 database is assigned one of the
301 following type affinities:</p>
302 <ul>
303 <li>TEXT</li>
304 <li>NUMERIC</li>
305 <li>INTEGER</li>
306 <li>REAL</li>
307 <li>BLOB</li>
308 </ul>
309
310 <p>(Historical note: The "BLOB" type affinity used to be called "NONE".
311 But that term was easy to confuse with "no affinity" and so it was
312 renamed.)
313
314 </p><p>A column with TEXT affinity stores all data using storage classes
315 NULL, TEXT or BLOB. If numerical data is inserted into a column with
316 TEXT affinity it is converted into text form before being stored.</p>
317
318 <p>A column with NUMERIC affinity may contain values using all five
319 storage classes. When text data is inserted into a NUMERIC column, the
320 storage class of the text is converted to INTEGER or REAL (in order of
321 preference) if the text is a well-formed integer or real literal, respectively.
322 If the TEXT value is a well-formed integer literal that is too large
323 to fit in a 64-bit signed integer, it is converted to REAL.
324 For conversions between TEXT and REAL storage classes, only the first
325 15 significant decimal digits of the number are preserved.
326 If the TEXT value is not a well-formed integer or real literal,
327 then the value is stored as TEXT.
328 For the purposes of this paragraph, hexadecimal integer
329 literals are not considered well-formed and are stored as TEXT.
330 (This is done for historical compatibility with versions of SQLite
331 prior to <a href="releaselog/3_8_6.html">version 3.8.6</a> 2014-08-15 where hexadecimal integer
332 literals were first introduced into SQLite.)
333 If a floating point value that can be represented exactly as an integer
334 is inserted into a column with NUMERIC affinity, the value is
335 converted into an integer.
336 No attempt is made to convert NULL or BLOB values.</p>
337
338 <p>A string might look like a floating-point literal with
339 a decimal point and/or exponent notation but as long as
340 the value can be expressed as an integer, the NUMERIC affinity will convert
341 it into an integer. Hence, the string '3.0e+5' is stored in a
342 column with NUMERIC affinity as the integer 300000, not as the floating
343 point value 300000.0.</p>
344
345 <p>A column that uses INTEGER affinity behaves the same as a column
346 with NUMERIC affinity. The difference between INTEGER and NUMERIC affinity
347 is only evident in a <a href="lang_expr.html#castexpr">CAST expression</a>: The expression
348 "CAST(4.0 AS INT)" returns an integer 4, whereas
349 "CAST(4.0 AS NUMERIC)" leaves the value as a floating-point 4.0.</p>
350
351 <p>A column with REAL affinity behaves like a column with NUMERIC
352 affinity except that it forces integer values into floating point
353 representation. (As an internal optimization, small floating point
354 values with no fractional component and stored in columns with REAL
355 affinity are written to disk as integers in order to take up less
356 space and are automatically converted back into floating point as
357 the value is read out.
358 This optimization is completely invisible at the SQL level and can only
359 be detected by examining the raw bits of the database file.)</p>
360
361 <p>A column with affinity BLOB does not prefer one storage class over
362 another and no attempt is made to coerce data from one storage class into
363 another.</p>
364
365 <a name="affname"></a>
366
367 <h2 id="determination_of_column_affinity"><span>3.1. </span>Determination Of Column Affinity</h2>
368
369 <p>For tables not declared as <a href="stricttables.html">STRICT</a>,
370 the affinity of a column is determined by the declared type
371 of the column, according to the following rules in the order shown:</p>
372
373 <ol>
374 <li><p>If the declared type contains the string "INT" then it
375 is assigned INTEGER affinity.</p>
376
377 </li><li><p>If the declared type of the column contains any of the strings
378 "CHAR", "CLOB", or "TEXT" then that
379 column has TEXT affinity. Notice that the type VARCHAR contains the
380 string "CHAR" and is thus assigned TEXT affinity.</p>
381
382 </li><li><p>If the declared type for a column
383 contains the string "BLOB" or if
384 no type is specified then the column has affinity BLOB.</p>
385
386 </li><li><p>If the declared type for a column
387 contains any of the strings "REAL", "FLOA",
388 or "DOUB" then the column has REAL affinity.</p>
389
390 </li><li><p>Otherwise, the affinity is NUMERIC.</p>
391 </li></ol>
392
393 <p>Note that the order of the rules for determining column affinity
394 is important. A column whose declared type is "CHARINT" will match
395 both rules 1 and 2 but the first rule takes precedence and so the
396 column affinity will be INTEGER.</p>
397
398 <h3 id="affinity_name_examples"><span>3.1.1. </span>Affinity Name Examples</h3>
399
400 <p>The following table shows how many common datatype names from
401 more traditional SQL implementations are converted into affinities by the five rules of the
402 previous section. This table shows only a small subset of the
403 datatype names that SQLite will accept. Note that numeric arguments
404 in parentheses that following the type name (ex: "VARCHAR(255)") are
405 ignored by SQLite - SQLite does not impose any length restrictions
406 (other than the large global <a href="limits.html#max_length">SQLITE_MAX_LENGTH</a> limit) on the length of
407 strings, BLOBs or numeric values.</p>
408
409 <blockquote>
410 <table border="1" cellpadding="5">
411 <tr><th>Example Typenames From The<br>CREATE TABLE Statement<br>
412 or CAST Expression
413 </th><th>Resulting Affinity
414 </th><th>Rule Used To Determine Affinity
415
416 </th></tr><tr><td align="center" valign="top">
417 INT<br>
418 INTEGER<br>
419 TINYINT<br>
420 SMALLINT<br>
421 MEDIUMINT<br>
422 BIGINT<br>
423 UNSIGNED BIG INT<br>
424 INT2<br>
425 INT8
426 </td><td align="center">INTEGER
427 </td><td align="center">1
428
429 </td></tr><tr><td align="center" valign="top">
430 CHARACTER(20)<br>
431 VARCHAR(255)<br>
432 VARYING CHARACTER(255)<br>
433 NCHAR(55)<br>
434 NATIVE CHARACTER(70)<br>
435 NVARCHAR(100)<br>
436 TEXT<br>
437 CLOB
438 </td><td align="center">TEXT
439 </td><td align="center">2
440
441 </td></tr><tr><td align="center" valign="top">
442 BLOB<br>
443 <i>no datatype specified</i>
444 </td><td align="center">BLOB
445 </td><td align="center">3
446
447 </td></tr><tr><td align="center" valign="top">
448 REAL<br>
449 DOUBLE<br>
450 DOUBLE PRECISION<br>
451 FLOAT
452 </td><td align="center">REAL
453 </td><td align="center">4
454
455 </td></tr><tr><td align="center" valign="top">
456 NUMERIC<br>
457 DECIMAL(10,5)<br>
458 BOOLEAN<br>
459 DATE<br>
460 DATETIME
461 </td><td align="center">NUMERIC
462 </td><td align="center">5
463 </td></tr></table>
464 </blockquote>
465
466 <p>Note that a declared type of "FLOATING POINT" would give INTEGER
467 affinity, not REAL affinity, due to the "INT" at the end of "POINT".
468 And the declared type of "STRING" has an affinity of NUMERIC, not TEXT.
469
470 <a name="expraff"></a>
471
472 </p><h2 id="affinity_of_expressions"><span>3.2. </span>Affinity Of Expressions</h2>
473
474 <p>Every table column has a type affinity (one of BLOB, TEXT, INTEGER,
475 REAL, or NUMERIC) but expressions do not necessarily have an affinity.
476
477 </p><p>Expression affinity is determined by the following rules:
478
479 </p><ul>
480 <li><p>The right-hand operand of an IN or NOT IN
481 operator has no affinity if the operand is a list, or has the same
482 affinity as the affinity of the result set expression if the operand
483 is a SELECT.
484
485 </p></li><li><p>When an expression is a simple reference to a column of a
486 real table (not a <a href="lang_createview.html">VIEW</a> or subquery) then the expression
487 has the same affinity as the table column.
488 </p><ul>
489 <li><p>Parentheses around the column name are ignored. Hence if
490 X and Y.Z are column names, then (X) and (Y.Z) are also considered
491 column names and have the affinity of the corresponding columns.
492 </p></li><li><p>
493 Any operators applied to column names, including the no-op
494 unary "+" operator, convert the column name into an expression which
495 always has no affinity. Hence even if X and Y.Z are column names, the
496 expressions +X and +Y.Z are not column names and have no affinity.
497 </p></li></ul>
498
499 </li><li><p>An expression of the form "CAST(<i>expr</i> AS <i>type</i>)"
500 has an affinity that is the same as a column with a declared
501 type of "<i>type</i>".
502
503 </p></li><li><p>A COLLATE operator has the same affinity as its left-hand side operand.
504
505 </p></li><li><p>Otherwise, an expression has no affinity.
506 </p></li></ul>
507
508 <a name="affview"></a>
509
510 <h2 id="column_affinity_for_views_and_subqueries"><span>3.3. </span>Column Affinity For Views And Subqueries</h2>
511
512 <p>The "columns" of a <a href="lang_createview.html">VIEW</a> or FROM-clause subquery are really
513 the expressions
514 in the result set of the <a href="lang_select.html">SELECT</a> statement that implements the VIEW
515 or subquery. Thus, the affinity for columns of a VIEW or subquery
516 are determined by the expression affinity rules above.
517 Consider an example:
518
519 </p><blockquote><pre>
520 CREATE TABLE t1(a INT, b TEXT, c REAL);
521 CREATE VIEW v1(x,y,z) AS SELECT b, a+c, 42 FROM t1 WHERE b!=11;
522 </pre></blockquote>
523
524 <p>The affinity of the v1.x column will be the same as the affinity
525 of t1.b (TEXT), since v1.x maps directly into t1.b. But
526 columns v1.y and v1.z both have no affinity, since those columns
527 map into expression a+c and 42, and expressions always have no
528 affinity.
529
530 <a name="affcompoundview"></a>
531
532 </p><h3 id="column_affinity_for_compound_views"><span>3.3.1. </span>Column Affinity For Compound Views</h3>
533
534 <p>When the <a href="lang_select.html">SELECT</a> statement that implements a <a href="lang_createview.html">VIEW</a> or
535 FROM-clause subquery is a <a href="lang_select.html#compound">compound SELECT</a> then the affinity of
536 each column of the VIEW or subquery will
537 be the affinity of the corresponding result column for
538 one of the individual SELECT statements that make up
539 the compound.
540 However, it is indeterminate which of the SELECT statements will
541 be used to determine affinity.
542 Different constituent SELECT statements might be used to determine
543 affinity at different times during query evaluation. The choice
544 might vary across different versions of SQLite. The choice might
545 change between one query and the next in the same version of SQLite.
546 The choice might be different at different times within the same
547 query. Hence, you can never be sure what affinity will be used
548 for columns of a compound SELECT that have different affinities in
549 the constituent subqueries.
550
551 </p><p>Best practice is to avoid mixing affinities in a compound SELECT
552 if you care about the datatype of the result. Mixing affinities in
553 a compound SELECT can lead to surprising and unintuitive results.
554 See, for example, <a href="https://sqlite.org/forum/forumpost/02d7be94d7">forum post 02d7be94d7</a>.
555
556 </p><h2 id="column_affinity_behavior_example"><span>3.4. </span>Column Affinity Behavior Example</h2>
557
558 <p>The following SQL demonstrates how SQLite uses column affinity
559 to do type conversions when values are inserted into a table.</p>
560
561 <blockquote>
562 <pre>
563 CREATE TABLE t1(
564 t TEXT, -- text affinity by rule 2
565 nu NUMERIC, -- numeric affinity by rule 5
566 i INTEGER, -- integer affinity by rule 1
567 r REAL, -- real affinity by rule 4
568 no BLOB -- no affinity by rule 3
569 );
570
571 -- Values stored as TEXT, INTEGER, INTEGER, REAL, TEXT.
572 INSERT INTO t1 VALUES('500.0', '500.0', '500.0', '500.0', '500.0');
573 SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1;
574 text|integer|integer|real|text
575
576 -- Values stored as TEXT, INTEGER, INTEGER, REAL, REAL.
577 DELETE FROM t1;
578 INSERT INTO t1 VALUES(500.0, 500.0, 500.0, 500.0, 500.0);
579 SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1;
580 text|integer|integer|real|real
581
582 -- Values stored as TEXT, INTEGER, INTEGER, REAL, INTEGER.
583 DELETE FROM t1;
584 INSERT INTO t1 VALUES(500, 500, 500, 500, 500);
585 SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1;
586 text|integer|integer|real|integer
587
588 -- BLOBs are always stored as BLOBs regardless of column affinity.
589 DELETE FROM t1;
590 INSERT INTO t1 VALUES(x'0500', x'0500', x'0500', x'0500', x'0500');
591 SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1;
592 blob|blob|blob|blob|blob
593
594 -- NULLs are also unaffected by affinity
595 DELETE FROM t1;
596 INSERT INTO t1 VALUES(NULL,NULL,NULL,NULL,NULL);
597 SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1;
598 null|null|null|null|null
599 </pre>
600 </blockquote>
601
602 <a name="comparisons"></a>
603
604 <h1 id="comparison_expressions"><span>4. </span>Comparison Expressions</h1>
605
606 <p>SQLite version 3 has the usual set of SQL comparison operators
607 including "=", "==", "&lt;", "&lt;=", "&gt;", "&gt;=", "!=", "",
608 "IN", "NOT IN", "BETWEEN", "IS", and "IS NOT", .
609
610 <a name="sortorder"></a>
611
612 </p><h2 id="sort_order"><span>4.1. </span>Sort Order</h2>
613
614 <p>The results of a comparison depend on the storage classes of the
615 operands, according to the following rules:</p>
616 <ul>
617 <li><p>A value with storage class NULL is considered less than any
618 other value (including another value with storage class NULL).</p>
619
620 </li><li><p>An INTEGER or REAL value is less than any TEXT or BLOB value.
621 When an INTEGER or REAL is compared to another INTEGER or REAL, a
622 numerical comparison is performed.</p>
623
624 </li><li><p>A TEXT value is less than a BLOB value. When two TEXT values
625 are compared an appropriate collating sequence is used to determine
626 the result. </p>
627
628 </li><li><p>When two BLOB values are compared, the result is
629 determined using memcmp().</p>
630 </li></ul>
631
632 <a name="compaff"></a>
633
634 <h2 id="type_conversions_prior_to_comparison"><span>4.2. </span>Type Conversions Prior To Comparison</h2>
635
636 <p>SQLite may attempt to convert values between the storage classes
637 INTEGER, REAL, and/or TEXT before performing a comparison.
638 Whether or not any conversions are attempted before the comparison takes
639 place depends on the type affinity of the operands.
640
641 </p><p>To "apply affinity" means to convert an operand to a particular storage
642 class if and only if the conversion does not lose essential information.
643 Numeric values can always be converted into TEXT. TEXT values
644 can be converted into numeric values if the text content is a well-formed
645 integer or real literal, but not a hexadecimal integer literal.
646 BLOB values are converted into TEXT values by simply interpreting
647 the binary BLOB content as a text string in the current database
648 encoding.
649
650 </p><p>Affinity is applied to operands of a comparison operator prior to
651 the comparison according to the following rules in the order shown:</p>
652
653 <ul>
654 <li><p>If one operand has INTEGER, REAL or NUMERIC affinity
655 and the other operand has TEXT or BLOB or no affinity
656 then NUMERIC affinity is applied to other operand.
657
658 </p></li><li><p>If one operand has TEXT affinity and the other has no affinity,
659 then TEXT affinity is applied to the other operand.
660
661 </p></li><li><p>Otherwise, no affinity is applied and both operands are compared
662 as is.</p>
663 </li></ul>
664
665 <p>The expression "a BETWEEN b AND c" is treated as two separate
666 binary comparisons "a &gt;= b AND a &lt;= c", even if that means
667 different affinities are applied to 'a' in each of the comparisons.
668 Datatype conversions in comparisons of the
669 form "x IN (SELECT y ...)" are handled as if
670 the comparison were really "x=y".
671 The expression "a IN (x, y, z, ...)" is equivalent to "a = +x OR
672 a = +y OR a = +z OR ...".
673 In other words, the values to the right of the IN operator (the "x", "y",
674 and "z" values in this example) are considered to have no affinity,
675 even if they happen to be column values or CAST expressions.
676 </p>
677
678 <h2 id="comparison_example"><span>4.3. </span>Comparison Example</h2>
679
680 <blockquote>
681 <pre>
682 CREATE TABLE t1(
683 a TEXT, -- text affinity
684 b NUMERIC, -- numeric affinity
685 c BLOB, -- no affinity
686 d -- no affinity
687 );
688
689 -- Values will be stored as TEXT, INTEGER, TEXT, and INTEGER respectively
690 INSERT INTO t1 VALUES('500', '500', '500', 500);
691 SELECT typeof(a), typeof(b), typeof(c), typeof(d) FROM t1;
692 text|integer|text|integer
693
694 -- Because column "a" has text affinity, numeric values on the
695 -- right-hand side of the comparisons are converted to text before
696 -- the comparison occurs.
697 SELECT a &lt; 40, a &lt; 60, a &lt; 600 FROM t1;
698 0|1|1
699
700 -- Text affinity is applied to the right-hand operands but since
701 -- they are already TEXT this is a no-op; no conversions occur.
702 SELECT a &lt; '40', a &lt; '60', a &lt; '600' FROM t1;
703 0|1|1
704
705 -- Column "b" has numeric affinity and so numeric affinity is applied
706 -- to the operands on the right. Since the operands are already numeric,
707 -- the application of affinity is a no-op; no conversions occur. All
708 -- values are compared numerically.
709 SELECT b &lt; 40, b &lt; 60, b &lt; 600 FROM t1;
710 0|0|1
711
712 -- Numeric affinity is applied to operands on the right, converting them
713 -- from text to integers. Then a numeric comparison occurs.
714 SELECT b &lt; '40', b &lt; '60', b &lt; '600' FROM t1;
715 0|0|1
716
717 -- No affinity conversions occur. Right-hand side values all have
718 -- storage class INTEGER which are always less than the TEXT values
719 -- on the left.
720 SELECT c &lt; 40, c &lt; 60, c &lt; 600 FROM t1;
721 0|0|0
722
723 -- No affinity conversions occur. Values are compared as TEXT.
724 SELECT c &lt; '40', c &lt; '60', c &lt; '600' FROM t1;
725 0|1|1
726
727 -- No affinity conversions occur. Right-hand side values all have
728 -- storage class INTEGER which compare numerically with the INTEGER
729 -- values on the left.
730 SELECT d &lt; 40, d &lt; 60, d &lt; 600 FROM t1;
731 0|0|1
732
733 -- No affinity conversions occur. INTEGER values on the left are
734 -- always less than TEXT values on the right.
735 SELECT d &lt; '40', d &lt; '60', d &lt; '600' FROM t1;
736 1|1|1
737 </pre>
738 </blockquote>
739
740 <p>All of the results in the example are the same if the comparisons are
741 commuted - if expressions of the form "a&lt;40" are rewritten
742 as "40&gt;a".
743
744 </p><h1 id="operators"><span>5. </span>Operators</h1>
745
746 <p>Mathematical operators (+, -, *, /, %, &lt;&lt;, &gt;&gt;,
747 &amp;, and |) interpret both operands as if they were numbers.
748 STRING or BLOB operands automatically convert into REAL or INTEGER values.
749 If the STRING or BLOB looks like a real number (if it has a decimal point
750 or an exponent) or if the value is outside the range that can be represented
751 as a 64-bit signed integer, then it converts to REAL. Otherwise the operand
752 converts to INTEGER.
753 The implied type conversion of mathematical operands is slightly different
754 from <a href="lang_expr.html#castexpr">CAST to NUMERIC</a> in that string and BLOB values that
755 look like real numbers but have no fractional part are kept as REAL
756 instead of being converted into INTEGER as they would be for <a href="lang_expr.html#castexpr">CAST to NUMERIC</a>.
757 The conversion from STRING or BLOB into REAL or INTEGER is performed
758 even if it is lossy and irreversible.
759 Some mathematical operators (%, &lt;&lt;, &gt;&gt;, &amp;, and |) expect
760 INTEGER operands. For those operators, REAL operands are converted into INTEGER
761 in the same way as a <a href="lang_expr.html#castexpr">CAST to INTEGER</a>.
762 The &lt;&lt;, &gt;&gt;, &amp;, and | operators always return an INTEGER (or NULL)
763 result, but the % operator returns either INTEGER or REAL (or NULL)
764 depending on the type of its operands.
765 A NULL operand on a mathematical operator yields a NULL result.
766 An operand on a mathematical operator that does not look in any way
767 numeric and is not NULL is converted to 0 or 0.0.
768 Division by zero gives a result of NULL.
769 </p>
770
771 <h1 id="sorting_grouping_and_compound_selects"><span>6. </span>Sorting, Grouping and Compound SELECTs</h1>
772
773 <p>When query results are sorted by an ORDER BY clause, values with storage
774 class NULL come first, followed by INTEGER and REAL values
775 interspersed in numeric order, followed by TEXT values in collating
776 sequence order, and finally BLOB values in memcmp() order. No storage
777 class conversions occur before the sort.</p>
778
779 <p>When grouping values with the GROUP BY clause values with
780 different storage classes are considered distinct, except for INTEGER
781 and REAL values which are considered equal if they are numerically
782 equal. No affinities are applied to any values as the result of a
783 GROUP by clause.</p>
784
785 <p>The compound SELECT operators UNION,
786 INTERSECT and EXCEPT perform implicit comparisons between values.
787 No affinity is applied to comparison operands for the implicit
788 comparisons associated with UNION, INTERSECT, or EXCEPT - the values
789 are compared as is.</p>
790
791 <a name="collation"></a>
792
793 <h1 id="collating_sequences"><span>7. </span>Collating Sequences</h1>
794
795 <p>When SQLite compares two strings, it uses a collating sequence or
796 collating function (two terms for the same thing) to determine which
797 string is greater or if the two strings are equal.
798 SQLite has three built-in collating functions: BINARY, NOCASE, and
799 RTRIM.</p>
800
801 <ul>
802 <li><b>BINARY</b> - Compares string data using memcmp(), regardless
803 of text encoding.</li>
804 <li><b>NOCASE</b> - Similar to binary, except that it uses
805 <a href="c3ref/stricmp.html">sqlite3_strnicmp()</a> for the comparison. Hence the 26 upper case
806 characters of ASCII are folded to their lower case equivalents before
807 the comparison is performed. Note that only ASCII characters
808 are case folded. SQLite does not attempt to do full
809 UTF case folding due to the size of the tables required.
810 Also note that any U+0000 characters in the string are considered
811 string terminators for comparison purposes.
812
813 </li><li><b>RTRIM</b> - The same as binary, except that trailing space
814 characters are ignored.</li>
815 </ul>
816
817 <p>An application can register additional collating functions using
818 the <a href="c3ref/create_collation.html">sqlite3_create_collation()</a> interface.</p>
819
820 <p>Collating functions only matter when comparing string values.
821 Numeric values are always compared numerically, and BLOBs are always
822 compared byte-by-byte using memcmp().</p>
823
824 <h2 id="assigning_collating_sequences_from_sql"><span>7.1. </span>Assigning Collating Sequences from SQL</h2>
825
826 <p>
827 Every column of every
828 table has an associated collating function. If no collating function
829 is explicitly defined, then the collating function defaults to BINARY.
830 The COLLATE clause of the <a href="lang_createtable.html#tablecoldef">column definition</a> is used
831 to define alternative collating functions for a column.
832 </p>
833
834 <a name="colrules"></a>
835
836
837 <p>
838 The rules for determining which collating function to use for a
839 binary comparison operator (=, &lt;, &gt;, &lt;=, &gt;=, !=, IS, and
840 IS NOT) are as follows:
841
842 </p><ol>
843 <li><p>If either operand has an explicit collating function assignment
844 using the postfix <a href="lang_expr.html#collateop">COLLATE operator</a>, then the explicit collating function
845 is used for comparison, with precedence to the collating function of the
846 left operand.</p></li>
847
848 <li><p>If either operand is a column, then the collating function of
849 that column is used with precedence to the left operand.
850 For the purposes of the previous sentence, a column name
851 preceded by one or more unary "+" operators and/or CAST operators
852 is still considered a column name.
853 </p></li>
854
855 <li><p>Otherwise, the BINARY collating function is used for comparison.
856 </p></li>
857 </ol>
858
859 <p>
860 An operand of a comparison is considered to have an explicit
861 collating function assignment (rule 1 above)
862 if any subexpression of the operand uses
863 the postfix <a href="lang_expr.html#collateop">COLLATE operator</a>. Thus, if a <a href="lang_expr.html#collateop">COLLATE operator</a> is used
864 anywhere in a comparison expression, the collating function defined
865 by that operator is used for string comparison regardless of what
866 table columns might be a part of that expression. If two or more
867 <a href="lang_expr.html#collateop">COLLATE operator</a> subexpressions appear anywhere in a comparison, the
868 left most explicit collating function is used regardless of how deeply the
869 COLLATE operators are nested in the expression and regardless of
870 how the expression is parenthesized.
871 </p>
872
873 <p>
874 The expression "x BETWEEN y and z" is logically
875 equivalent to two comparisons "x &gt;= y AND x &lt;= z" and works with
876 respect to collating functions as if it were two separate comparisons.
877 The expression "x IN (SELECT y ...)" is handled in the same way as the
878 expression "x = y" for the purposes of determining the collating sequence.
879 The collating sequence used for expressions of the form
880 "x IN (y, z, ...)" is the collating sequence of x.
881 If an explicit collating sequence is required on an IN operator
882 it should be applied to the left operand, like this:
883 "x COLLATE nocase IN (y,z, ...)".
884 </p>
885
886 <p>
887 Terms of the ORDER BY clause that is part of a <a href="lang_select.html">SELECT</a>
888 statement may be assigned a collating sequence using the
889 <a href="lang_expr.html#collateop">COLLATE operator</a>, in which case the specified collating function is
890 used for sorting.
891 Otherwise, if the expression sorted by an ORDER BY clause is
892 a column, then the collating sequence of the column is used to
893 determine sort order. If the expression is not a column and has no
894 COLLATE clause, then the BINARY collating sequence is used.
895 </p>
896
897 <h2 id="collation_sequence_examples"><span>7.2. </span>Collation Sequence Examples</h2>
898 <p>
899 The examples below identify the collating sequences that would be used to
900 determine the results of text comparisons that may be performed by various
901 SQL statements. Note that a text comparison may not be required, and no
902 collating sequence used, in the case of numeric, blob or NULL values.
903 </p>
904 <blockquote>
905 <pre>
906 CREATE TABLE t1(
907 x INTEGER PRIMARY KEY,
908 a, /* collating sequence BINARY */
909 b COLLATE BINARY, /* collating sequence BINARY */
910 c COLLATE RTRIM, /* collating sequence RTRIM */
911 d COLLATE NOCASE /* collating sequence NOCASE */
912 );
913 /* x a b c d */
914 INSERT INTO t1 VALUES(1,'abc','abc', 'abc ','abc');
915 INSERT INTO t1 VALUES(2,'abc','abc', 'abc', 'ABC');
916 INSERT INTO t1 VALUES(3,'abc','abc', 'abc ', 'Abc');
917 INSERT INTO t1 VALUES(4,'abc','abc ','ABC', 'abc');
918
919 /* Text comparison a=b is performed using the BINARY collating sequence. */
920 SELECT x FROM t1 WHERE a = b ORDER BY x;
921 --result 1 2 3
922
923 /* Text comparison a=b is performed using the RTRIM collating sequence. */
924 SELECT x FROM t1 WHERE a = b COLLATE RTRIM ORDER BY x;
925 --result 1 2 3 4
926
927 /* Text comparison d=a is performed using the NOCASE collating sequence. */
928 SELECT x FROM t1 WHERE d = a ORDER BY x;
929 --result 1 2 3 4
930
931 /* Text comparison a=d is performed using the BINARY collating sequence. */
932 SELECT x FROM t1 WHERE a = d ORDER BY x;
933 --result 1 4
934
935 /* Text comparison 'abc'=c is performed using the RTRIM collating sequence. */
936 SELECT x FROM t1 WHERE 'abc' = c ORDER BY x;
937 --result 1 2 3
938
939 /* Text comparison c='abc' is performed using the RTRIM collating sequence. */
940 SELECT x FROM t1 WHERE c = 'abc' ORDER BY x;
941 --result 1 2 3
942
943 /* Grouping is performed using the NOCASE collating sequence (Values
944 ** 'abc', 'ABC', and 'Abc' are placed in the same group). */
945 SELECT count(*) FROM t1 GROUP BY d ORDER BY 1;
946 --result 4
947
948 /* Grouping is performed using the BINARY collating sequence. 'abc' and
949 ** 'ABC' and 'Abc' form different groups */
950 SELECT count(*) FROM t1 GROUP BY (d || '') ORDER BY 1;
951 --result 1 1 2
952
953 /* Sorting or column c is performed using the RTRIM collating sequence. */
954 SELECT x FROM t1 ORDER BY c, x;
955 --result 4 1 2 3
956
957 /* Sorting of (c||'') is performed using the BINARY collating sequence. */
958 SELECT x FROM t1 ORDER BY (c||''), x;
959 --result 4 2 3 1
960
961 /* Sorting of column c is performed using the NOCASE collating sequence. */
962 SELECT x FROM t1 ORDER BY c COLLATE NOCASE, x;
963 --result 2 4 3 1
964 </pre>
965 </blockquote>
966
967