Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am shifting my database to MS SQL Server 2008 R2, When I am trying to save long length string then it is giving me the error for Maximum length, while i have set the datatype of that column as "text" after it i replaced it with "varchar(max)" but no solution there. kindly provide me a solution how to resolve this is...
According to ANSI SQL standard, double quotes are used (if *necessary*) for object identifiers (ex. `UPDATE "hotel" ...)` and not as string delimiters (`"Overview of Park Central ..."`). SQL Server has this behavior when `QUOTED_IDENTIFIER` is `ON`. **Edit 1:** The usage of single and double quotation marks as delimit...
If you don't want to change double quotes to single quotes add following two lines in the begging of the script ``` SET QUOTED_IDENTIFIER OFF SET ANSI_NULLS ON ```
The identifier that starts with ...... is too long. Maximum length is 128
[ "", "sql", "sql-server", "" ]
I want to add multiple items/rows in SQLite using single insert query, ``` insert into suppliers (supoliers_no,supply_name,city,phone_no) values (1,'Ali','amman',111111), (2,'tariq','amman',777777), (3,'mohmmed','taiz',null); ``` Is it possible using Sqlite?
It should be:- ``` insert into suppliers (supoliers_no,supply_name,city,phone_no) values (1,'Ali','amman',111111); insert into suppliers (supoliers_no,supply_name,city,phone_no) values (2,'tariq','amman',777777); insert into suppliers (supoliers_no,supply_name,city,phone_no) values (3,'mohmmed','taiz',null); ``` ...
Multiple insert rows in one line code is `INSERT INTO TableName ( Column1, Column2,Column3 ) VALUES ( Value1, Value2 ,Value3), ( Value1, Value2,Value3 );` In your case Code is correct but `(3,'mohmmed','taiz',null);` try with give some value. and you can also take reference from here [Inserting multiple rows in a s...
Insert multiple set of values using Sqlite
[ "", "sql", "sqlite", "" ]
Below is my SQL I would like to execute. I'd like to avoid doing multiple requests for that and i'm pretty sure it's possible… ``` First table : products_categories (category_id, category_infos…) Second table : products_categories_relations (product_id, category_id) Third table : products (product_id, published, produ...
``` SELECT pc.`category_id` FROM `#__products_categories` AS pc LEFT JOIN `#__products_categories_relations` pcr ON pc.`category_id` = pcr.`category_id` LEFT JOIN (SELECT product_id, MAX(published) published FROM products GROUP BY product_id HAVING published = 0) p ON pcr.product_id = ...
``` SELECT pc.* FROM products_categories pc INNER JOIN products_categories_relations pcr ON (pc.category_id = pcr.category_id) INNER JOIN products p ON (pcr.product_id = p.product_id AND published = 0) EXCEPT SELECT pc.* FROM products_categories pc INNER JOIN products_categories_relations pcr ON (pc.category_id = pcr.c...
Hard SQL query - Rows with no matching in another table OR with items not published in another one
[ "", "mysql", "sql", "" ]
I have say 3 tables, which have a key that links through all three like so... ``` select a.call_id, b.name, c.year from table1 a, table2 b, table3 c where a.call_id = b.call_id and b.call_id = c.call_id and a.call_id = 123 ``` The problem is table 3 doesn't have a record that matches the id of 123, thus the entire qu...
Yes, you have to use `LEFT` join: ``` select a.call_id, b.name, c.year from table1 a JOIN table2 b ON (a.call_id = b.call_id) LEFT JOIN table3 c ON (b.call_id = c.call_id) WHERE a.call_id = 123; ``` Read more about joins here: [Visual Explanation of Joins by Jeff Atwood](http://www.codinghorror.com/blog/2...
I guess you just need to translate this to JOIN: ``` SELECT a.call_id, b.name, c.year from table1 a JOIN table2 b ON a.call_id = b.call_id LEFT JOIN table3 c ON and b.call_id = c.call_id WHERE a.call_id = 123 ```
Oracle SQL: joining with an empty table
[ "", "sql", "oracle", "join", "" ]
I wrote the below SQL query with a `LIKE` condition: ``` SELECT * FROM Manager WHERE managerid LIKE '_%' AND managername LIKE '%_%' ``` In the `LIKE` I want to search for any underscores **`%_%`**, but I know that my columns' data has no underscore characters. * Why does the query give me all the records from the ta...
Modify your `WHERE` condition like this: ``` WHERE mycolumn LIKE '%\_%' ESCAPE '\' ``` This is one of the ways in which Oracle supports escape characters. Here you define the escape character with the `escape` keyword. For details see [this link on Oracle Docs](https://docs.oracle.com/cd/B10501_01/text.920/a96518/cqs...
The underscore is the [wildcard in a `LIKE`](http://technet.microsoft.com/en-us/library/ms174424.aspx) query for one arbitrary character. Hence `LIKE %_%` means "give me all records with at least one arbitrary character in this column". You have to escape the wildcard character, in sql-server with `[]` around: ``` S...
Why does using an Underscore character in a LIKE filter give me all the results?
[ "", "sql", "sql-server", "" ]
From **performance perspective** , is this the best way to write the following query concerning the nested query : --- ``` SELECT a.meg,a.currency FROM alt6sal a WHERE a.meg_code IN (1,2) AND a.sal_year = (SELECT MAX(ia.sal_year) FROM alt6sal ia WHERE a.emp_num = ia.emp_num ) AND a.sal_mon = (SELECT MAX(ia.sal_mon...
If you can avoid correlated subquery, the better the performance, example of non-correlated subquery: ``` SELECT a.meg,a.currency FROM alt6sal a join ( select ia.emp_num, max(ia.sal_year) as sal_year_max from alt6sal ia group by ia.emp_num ) the_year_max on a.emp_num = the_year_max.emp_num and a.sal_ye...
You can try this - ``` SELECT meg, currency FROM ( SELECT a.meg,a.currency, dense_rank() over (PARTITION BY a.emp_num ORDER BY a.sal_year desc) year_rank, dense_rank() over (PARTITION BY a.emp_num ORDER BY a.sal_mon desc) mon_rank FROM alt6sal a WHERE a.meg_code IN (1,2) ) WHERE year_rank = 1 AND mon_rank = 1; ```
nested query performance alternatives
[ "", "sql", "performance", "informix", "subquery", "" ]
Having a bit of trouble with an SQL query I am trying to create. The table format is as follows, ``` ID | Data Identifier | Date Added | Data Column 1 | 1001 | 15400 | Newest Value 1 | 1001 | 15000 | Oldest Value 1 | 1001 | 15200 | Older Value 1 | 1002 | ...
It seems as if you want to GROUP BY and maybe a self join onto the table. I have the following code for you: ``` -- Preparing a test table INSERT INTO #tmpTable(ID, Identifier, DateAdded, DataColumn) SELECT 1, 1001, 15400, 'Newest Value' UNION SELECT 1, 1001, 15000, 'Oldest Value' UNION SELECT 1, 1001, 15200, 'Older...
You need to create a primary key column on your table that will not be used as an aggregate. Then you can create a [CTE](http://technet.microsoft.com/en-us/library/ms190766(v=sql.105).aspx) to select the rows required and then use it to select the data. The aggregate function `MIN(ABS(15500 - DateAdded))` will return ...
SQL inner join using multiple in statements on single table
[ "", "sql", "join", "inner-join", "" ]
there are date values in the below format,in one of the sql server 2000 tables ``` 10/1/2013 10:39:14 PM 10/1/2013 6:39:04 PM 10/1/2013 8:19:31 AM 10/1/2013 3:35:40 AM ``` how to convert the above format data values into a 24hour date format,as shown below ``` 10/1/2013 10:39 10/1/2013 18:39 10/1/2013 8:19 10/1/2...
Try this: First convert `varchar` date to `datetime` and then you can manipulate it in the way you want as: ``` -- CONVERT TO DATETIME TO GET 24HR FORMAT SELECT CONVERT(DATETIME, '10/1/2013 6:39:04 PM', 0) -- Concatenate in required format SELECT CONVERT(VARCHAR(10), CONVERT(DATETIME, '10/1/2013 6:39:04 PM', 0), ...
In SQL Server 2012, we can use Format function to have suitable date time format. Use capital letter 'HH:mm:ss' for 24 hour date time format. Example - **Query (24 hour format):** ``` Select Format(cast('2016-03-03 23:59:59' as datetime),'dd-MMM-yyyy HH:mm:ss','en-us'). ('HH:mm:ss' in Capital letters) ``` **Result*...
Convert a 12 hour format to 24 hour format in sql server
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2005", "sql-server-2008-r2", "" ]
I know this is bad, I just don't know how to re-write it... any help appreciated! ``` DECLARE @i INT, @var VARCHAR(max) SET @i = 0 WHILE 1 = 1 BEGIN INSERT INTO mrs.dbo.nav_worldcheck_results ("counter", "entity no", "entity first name", "en...
It doesn't look like you can optimize out your function call. Potentially you could consider pre computing this value if the query needs to be run regularly and the data doesn't change. I recommend that you read a little more about joins and determine if a cross cartesian is really necessary in your case(most of the t...
Thanks all for looking and taking the time to reply. I've actually done as Deadron suggested and used a mix of inner join using soundex as the relationship rather than the cross join. I've also added in the use of "difference" into the where clause rather than my Jaro function and performance has improved dramaticall...
Avoid Repeated Function call in WHERE Clause
[ "", "sql", "t-sql", "function", "" ]
I have the following query. ``` SELECT parent.id AS 'id', parent.CA_NAME as 'name', node.level AS 'level', midpoint.level AS 'midpointlevel', SUM(ad.id IS NOT NULL) AS 'count' FROM category AS parent, category AS midpoint, category AS node LEFT JOIN ad ON ad.id=node.id AND ad.status='A' WHERE (node.`LEFT` BETWEEN pare...
The easiest way is to use a simple subquery: ``` SELECT id, name, -- midpointlevel, <-- commented out, since we don't need this column level, count FROM ( SELECT parent.id AS 'id', parent.CA_NAME as 'name', node.level AS 'level', midpoint.level AS 'midpointlevel', SUM(ad.id IS NOT NU...
SELECT column\_name, aggregate\_function(column\_name) FROM table\_name WHERE column\_name operator value GROUP BY column\_name HAVING aggregate\_function(column\_name) operator value; Refer above syntax
Ignore Field used in HAVING clause on SELECT
[ "", "mysql", "sql", "having-clause", "" ]
The checksum is returning **null** in the program. And also when i try executing only the query.. i get ``` Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value 'Audit C recorded' to data type tinyint. ``` .. Can you please help me on this ``` SELECT CAST(ABS(CHECKSUM(Indicator)) % ...
``` SELECT CAST(ABS(CHECKSUM(Indicator)) % 220 AS TINYINT) AS Indicator, CAST(CIndicator AS VARCHAR(100)) AS CIndicator, CAST(ABS(CHECKSUM(SK_IndicatorL2)) % 220 AS TINYINT) AS SK_IndicatorL2, CAST(IndicatorL2 AS varchar(100)) AS IndicatorL2 FROM ( VALUES ('A...
I think she is trying to get the id and the name metric for this query. I am also getting the data type error.. CAST(ABS(CHECKSUM(Indicator)) % 450 as TinyInt) as an id number if i am not wrong
Abs and checksum in tsql
[ "", "sql", "t-sql", "" ]
I want to find rows (records) which have a specific vlaue (S) in a column (Type), and insert multiple rows (e.g. 2) based on that row in the same table. For example, in tabe t1 below, I want for each row of type 'S', 2 rows be inserted with same ID and Price, new Counter value (no specific requirement for this filed, ...
You just have to play **twice** this command: ``` insert into epn with w(max) as ( select max(t.counter) from t -- useful to get max counter value ) select t.id, w.max + rownum, 'B', t.price -- max + rownum then gives new values from t, w where t.type != 'B'; -- Avoid duplicating rows added 1st time ``` This gives:...
You need an insert select statement: ``` insert into t1 (ID, Counter, Type, Price) select ID, Counter+1, 'B', Price from t1 where Type = 'S' union all select ID, Counter+2, 'B', Price from t1 where Type = 'S'; ``` EDIT: Here is a statement that matches your criteria mentioned in your remark below. It gets the maximum...
How to insert multiple new records based on record(s) already in the table (in Oracle)?
[ "", "sql", "oracle", "insert", "multiple-records", "" ]
Suppose Table domains contains a cloumn 'dname'. It consists of 'india.com', russia.net', 'brazil.com', 'canada.biz' etc. I need to update table 'domain' where rows of column 'name' ends with .com. Please help
``` UPDATE domains SET col_name = 'column_value' WHERE dname LIKE '%.com'; ``` Syntax for this one is ``` UPDATE table_name SET col_name = 'column_value' WHERE column_name LIKE '%___'; ```
Try this:: ``` update domain set column='your value' where `name` like '%.com' ```
How update columns that ends with particular text?
[ "", "mysql", "sql", "conditional-statements", "where-clause", "" ]
I intend to make an app which is a sort of dictionnary for a slang/a dialect. There are not many words (less than 1000). To store the data, I have 2 solutions : * storing data in a clean sqlite database (which I use to do in my apps) * storing data in 26 xml files according to you, which solution would be the most fl...
1.For Better performance you must use sqlite insted of xml. 2.xml is more complex and you have to parse data by reading a tag, so its decrease performance and increase complexity.
Using sqlite database has more flexibility over storing in xmls 1. you can manage the data easily. other operations like searching, adding more, or deleting and related operations will be easier 2. you wont need to handle the store operations manually. if you use xmls then you need to store those separately which will...
xml or sql for small android databases?
[ "", "android", "sql", "xml", "sqlite", "" ]
I am trying to display data from 3 separate tables. **1.** product\_master that contain data regarding products like image,price,quantity,etc. **2.** attribute\_master that contain only attribute\_id and attribute\_name, **3.** product\_attrib\_master that contain data like prod\_id i.e foreign key, attribute\_id i....
Hello you need to add **WHERE** clause that will apply filter on resulted data. **WHERE** clause with **AND** that told sql engine that I want filtered data based on clause. ``` SELECT pm.prod_name, am.attribute_name, pa.product_attribute_value FROM product_attrib_master pa LEFT JOIN attribute_ma...
You need to add a where clause to your query. Try this:: ``` SELECT pm.prod_name, am.attribute_name, pa.product_attribute_value FROM product_attrib_master pa LEFT JOIN attribute_master am ON pa.attribute_id = am.attribute_id LEFT JOIN product_master pm ON pa.prod_id=pm.prod_id WHERE pm.prod_name ='Nokia Lumia ...
How to display record or data of single item from 3 joins
[ "", "mysql", "sql", "join", "left-join", "" ]
I have a Table\_A and Table\_B as below, how can I create a UNION to generate a result set likes Table\_C, so that the original content of the columns in Table\_A and Table\_B are kept. Table\_A: ``` ID High_Level_Text ------------------------- 01 High Level Text One 02 High Level Text Two 03 High Level T...
You can do: ``` select a.id as "ID", null as "KEY", a.High_level_text as "High_level_text", null as "Low_Level_Text" from table_a a union select b.id, b.key, null, b.Low_Level_Text from table_b b order by 1, 2 ``` `sqlfiddle demo` This sets the columns you want in your result in the first `select` (the ...
Try this: ``` SELECT ID, NULL as Key, High_Level_Text, NULL as Low_Level_Text FROM Table_A UNION SELECT ID, Key, NULL as High_Level_Text, Low_Level_Text FROM Table_B ORDER BY ID ``` Check this [SQL FIDDLE DEMO](http://sqlfiddle.com/#!6/4fc7b/1)
Combine two tables without ruin the content of original columns
[ "", "sql", "database", "union", "" ]
EDIT: Please see the edit below for the full code, the first one works. This might be a different problem that what was is in the title. I am trying to put a cursor's count result into an integer, but the integer always stays at 0. ``` DECLARE v_count int := 0; CURSOR logins IS SELECT count(*) FROM big_...
The problem was that I didn't fully understand how cursors worked. I replaced the cursor with a temporary table in which I put my static query : ``` CREATE TABLE apps.audit_custom as select [...] ``` Then I query this table in my LOOP, as such: ``` SELECT count(*) into v_count FROM apps.audit_custom ...
I modified your code a little, this works.. ``` DECLARE v_count int := 0; CURSOR logins IS SELECT count(*) FROM big_table; BEGIN OPEN logins; loop FETCH logins into v_count; IF v_count >= 10 THEN DBMS_OUTPUT.PUT_LINE ('Hi mom'); exit; END IF; end loop; CLOSE logins; END; ``` you forgo...
PL/SQL cursor: Fetch count into an integer, bad syntax?
[ "", "sql", "oracle", "plsql", "cursor", "" ]
I'm listing questions with this ``` SELECT q.qTitle, q.qDescription, q.qCreatedOn, u.uCode, u.uFullname, qcat.qcatTitle, q.qId, q.qStatus FROM tblQuestion AS q INNER JOIN tblUser AS u ON q.uId = u.uId INNER JOIN tblQuestionCategory AS qcat ON q.qcatId = qcat.qcatId WHERE (q.qStatus = 1) ORDER BY q.qCreatedOn DESC...
As found out in the comments the reason for the error is because of the fact that SQL Server 2008 does not support it. You may try to change the query according to SQL Server 2012. Something like this:- ``` SELECT column1 FROM ( SELECT column1, ROW_NUMBER() OVER (ORDER BY column_id) AS x FROM ...
For people using Entity Framework, particulary database first, this error can occur if you develop with SQL 2012 but deploy to an earlier version. The problem will occur if you use Take...Skip functionality, as SQL 2012 has a new syntax for this. See: <http://erikej.blogspot.co.uk/2014/12/a-breaking-change-in-entity-...
"Incorrect syntax near 'OFFSET'" modift sql comm 2012 to 2008
[ "", "sql", "sql-server", "sql-server-2008", "paging", "" ]
How can I cast a decimal value to float without getting the result in scientific notation? For example, if my value is `0.000050` as a decimal, when I cast it to float I get `5E-05` I would like to see `0.00005`
This has nothing to do with converting to float. It has to do with converting to text. You need to look at the [`str()`](http://msdn.microsoft.com/en-us/library/ms189527.aspx) function: ``` str( float_expression , total-width , number-of-decimal-places ) ``` where * *float-expression* means what you think it means, ...
``` ALTER FUNCTION [dbo].[fnExpStringToDecimal] ( @Number AS varchar(50) ) Returns Decimal(18,7) BEGIN RETURN (SELECT IIF(CHARINDEX ('E', @Number)> 0,CAST(SUBSTRING(@Number, 1, CHARINDEX ('E', @Number)-1)AS DECIMAL(18,7)) * POWER( 10.0000000,CAST(SUBSTRING(@Number, CHARINDEX ('E', @Number)+1, LEN(@Number)) AS DEC...
Sql cast to float without scientific notation
[ "", "sql", "sql-server", "" ]
Is there a way to simplify this script so that the CASE statements are not duplicated? It can look acceptable in this shortened example but in reality the CASE statement is much longer as I have cases for "every 2 weeks, "every 4 weeks", "monthly", etc. I am using SQL Server and a WHILE statement for performance reason...
Yes, a CTE should help. Try changing your INSERT statement to: ``` WITH cte as (SELECT CASE WHEN Recurrence = 'Daily' THEN DATEADD(DAY, @Interval, @theStartDate) WHEN Recurrence = 'Weekly' THEN DATEADD(WEEK, @Interval, @theStartDate) END AS EventDat...
You can wrap this in a function: ``` Create Function dbo.IntervalEnd( @recurrence varchar(10), @interval int, @startDate date -- or whatever data type you're using for dates ) returns date as begin return case when @recurrence = 'Daily' then dateadd(day, @interval, @startDate) when @rec...
How to avoid repetitive CASE statements in SQL WHILE loop doing INSERT
[ "", "sql", "sql-server", "t-sql", "" ]
``` SELECT produkte_eintraege.id, produkte_eintraege.hersteller, produkte_eintraege.titel, produkte_eintraege.img_url FROM produkte_eintraege JOIN produkte_eigenschaften ON produkte_eintraege.id = produkte_eigenschaften.produkte_eintraege_id WHERE (produkte_eigenschaften.eigenschaften_merkmale_id = 1 OR ...
Taking into account your comments to Walter's answer, which you should've put in your question in the first place, to achieve your goal you have to `GROUP BY` product id and put your conditions in `HAVING` clause ``` SELECT produkte_eintraege_id FROM produkte_eigenschaften -- WHERE eigenschaften_merkmale_id IN(1, 2...
In your query you have ``` WHERE (produkte_eigenschaften.eigenschaften_merkmale_id = 1 OR produkte_eigenschaften.eigenschaften_merkmale_id = 2) AND (produkte_eigenschaften.eigenschaften_merkmale_id = 3) ORDER by hits DESC ``` To paraphrase the query you are saying ``` SELECT * FROM a join b WHERE (a.id=1 OR a.id=...
Inner join multiple entries in table comparison
[ "", "mysql", "sql", "join", "" ]
im working on a select. I've got a table called vriend and a table called gebruiker. now i got 2 select that give me the result i want but i want to merge them together ``` SELECT g.naam,g.gebruikerID FROM gebruiker g INNER JOIN vriend v on g.gebruikerID = v.gebruikerID_Jezelf WHERE g.gebruikerID IN(SELECT gebruike...
``` SELECT g.naam,g.gebruikerID ,g2.naam,g2.gebruikerID FROM gebruiker g , gebruiker g2, vriend v WHERE g.gebruikerID = v.gebruikerID_Jezelf OR g2.gebruikerID = v.gebruikerID_Persoon AND g.gebruikerID IN(SELECT gebruikerID_Jezelf FROM vriend) OR g2.gebruikerID IN(SELECT gebruikerID_Persoon FROM vriend); ```
``` SELECT g.naam, g.gebruikerID , g2.naam, g2.gebruikerID FROM vriend v JOIN gebruiker g1 on g1.gebruikerID = v.gebruikerID_Jezelf JOIN gebruiker g2 ON g2.gebruikerID = v.gebruikerID_Persoon ; ```
merge 2 selects into 1
[ "", "sql", "database", "oracle", "select", "" ]
I have a database and a lot of tables inside it. I wrote definition into the each table and column's definition part. And now using query I want to see all table and columns definition. Can you please help me?
If you're using SqlServer. ``` SELECT obj.name, cols.name as columnname from dbname.sys.objects as obj inner join dbname.sys.columns as cols on obj.object_id = cols.object_id where obj.type='U' ```
try this to get the definition of table in SQL... > sp\_help 'tableName' example `sp_help 'MyTable'` We can also do same thing as ``` exec sp_help 'MyTable' ``` Because **sp\_help** is a pre define *stored processor* and we can execute stored processor using "**exec**" keyword or also can use "**execute**" keyword
Getting the definition of the tables and columns via a SQL statement
[ "", "sql", "sql-server-2008", "" ]
I've got a query in which I am returning multiple rows for a given event, for example: ``` ID | DateTime | String 1017436 | 2013-09-13 05:19:20.000 | Hello 1017436 | 2013-09-13 11:49:00.000 | World ``` I want the result to contain only the *earliest* occurre...
You can use window functions for this, either `ROW_NUMBER()` or `MIN()`. The idea is to partition the rows by the ID - `OVER (PARTITION BY id)` - and then either assign row numbers (ordered by the datetime) or find the minimum datetime per ID. Solution with `ROW_NUMBER()`: ``` ; WITH cte AS ( SELECT id, datetime, s...
You can use `ROW_NUMBER()` which generates sequential number that you can filter with. ``` SELECT ID, DateTime, String FROM ( SELECT ID, DateTime, String, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY DateTime) RN FROM tableName ) a WHERE RN = 1 ``` ...
Select row with the earliest date
[ "", "sql", "sql-server", "" ]
Just wondering if the way I put COMMIT in the code block is appropriate or not? Should I put them when it finished loop or after each insert statement or after the if else statement? ``` FOR VAL1 IN (SELECT A.* FROM TABLE_A A) LOOP IF VAL1.QTY >= 0 THEN INSERT INTO TEMP_TABLE VALUES('MORE OR EQUAL THAN 0'); COM...
Generally, committing in a loop is not a good idea, especially after every DML in that loop. Doing so you force oracle(LGWR) to write data in redo log files and may find yourself in a situation when other sessions hang because of `log file sync` wait event. Or facing `ORA-1555` because undo segments will be cleared mor...
It is rarely appropriate; say your insert into TEMP\_TABLE succeeds but your insert into AUDIT\_TABLE fails. You then don't know where you are at all. Additionally, commits will increase the amount of time it takes to perform an operation. It would be more normal to do everything within a single transaction; that is r...
PL/SQL Oracle Stored Procedure loop structure
[ "", "sql", "oracle", "plsql", "" ]
Using MS SQL 2012 I want to do something like ``` select a, b, c, a+b+c d ``` However a, b, c are complex computed columns, lets take a simple example ``` select case when x > 4 then 4 else x end a, ( select count(*) somethingElse) b, a + b c order by c ``` I hope that makes sense
I would probably do this: ``` SELECT sub.a, sub.b, (sub.a + sub.b) as c, FROM ( select case when x > 4 then 4 else x end a, (select count(*) somethingElse) b FROM MyTable ) sub ORDER BY c ```
You can use a nested query or a common table expression (CTE) for that. The CTE syntax is slightly cleaner - here it is: ``` WITH CTE (a, b) AS ( select case when x > 4 then 4 else x end a, count(*) somethingElse b from my_table ) SELECT a, b, (a+b) as c FROM CTE ORDER BY c ```
Can I add multiple columns to Totals
[ "", "sql", "sql-server", "" ]
Can we optimize this query any further: I need to get: ``` SELECT * FROM table1 WHERE (column1, column2) in (SELECT c1, c2 FROM table2); ``` Since the above query is not supported: I have the following query: ``` SELECT * FROM table1 join (SELECT c1, c2 from table2) as table3 ON table1.column1 = c1 and table1....
The answer is NO. You've already got the best query. A JOIN is usually the fastest option. The missing column alias would result in a syntax error, though. Fixed and simplified with aliases and the simpler `USING` clause: ``` SELECT * FROM table1 t1 JOIN ( SELECT c1 AS column1, min(c2) AS column2 FROM ...
``` SELECT * from table1 t1 WHERE EXISTS (select * from table2 ex WHERE t1.column1 = ex.c1 and t1.column2 = ex.c2 ); ``` UPDATE: and here for the MIN(c2) case: ``` SELECT * from table1 t1 WHERE EXISTS (select * from table2 ex WHERE ex.c1 = t1.column1 and ex.c2 = t1.column2 ) AND NOT EXIST...
Select for multiple fields with "IN" expression
[ "", "sql", "postgresql", "join", "greatest-n-per-group", "" ]
How to count the change in a `sql server` column like I have `Ignition` value Ignition 1 1 0 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0...
Simplest and shortest way for SQL server 2008 I know is: ``` with cte as ( select row_number() over(partition by Ignition order by Id) as rn1, row_number() over(order by Id) as rn2 from Table1 ) select count(distinct rn2 - rn1) - 1 from cte ``` Or, as @MartinSmith pointed out: ``` with cte as...
**Step 1:** use the `Row_Number()` function to provide a complete (un-broken) sequence of numbers, according to our order ``` SELECT ignition , id , Row_Number() OVER (ORDER BY id ASC) As row_num FROM your_table ``` **Step 4:** Make this a Common-Table Expression (CTE) so we can refer to the derived `row_...
Count number of occurrences in a bit column in sql
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "sql-server-2012", "" ]
This is my query of dynamically calculated fields: ``` SELECT 5 * (`Mean (all)` +0.01735568 )/(0.07268901) AS rank1, 5 * (`CVaR 95` +0.51612 )/(0.53212) AS rank2, 5 * (`Hurst` - 0.2 )/(0.7717653) AS rank3, 5 * (`MaxDD` +6.200000762939453 )/(16.200000762939) AS rank4, 5 * (`Positive % 12` - 0.3 )/(1) AS rank5 FROM ...
In MySQL, you cannot reference other aliases, but you can define variables in the select, so try this instead: ``` SELECT @rank1 := 5 * (`Mean (all)` +0.01735568 )/(0.07268901) AS rank1, @rank2 := 5 * (`CVaR 95` +0.51612 )/(0.53212) AS rank2, @rank3 := 5 * (`Hurst` - 0.2 )/(0.7717653) AS rank3, @rank4 :...
You can't use an alias in the same `SELECT` statement, put it inside a subquery instead, like this: ``` SELECT rank1, rank2, rank3, rank4, rank5, rank1 + rank2 + rank3 + rank4 + rank5 AS rank FROM ( SELECT 5 * (`Mean (all)` +0.01735568 )/(0.07268901) AS rank1, 5 * (`CVaR 95` +0.51612 )/(0.53212) AS rank2, ...
Sum of dynamically generated fields in MySQL query
[ "", "mysql", "sql", "" ]
Can somebody tell me how to extract my table definitions using SQL? I want to extract the datatypes of all my tables and other information from my Oracle schema. I have about 100 tables. I need the complete documentation of my Oracle Schema. My schema name IS "cco". Can I do this by SQL? I am using Toad for Data ana...
You can try this - ``` select * from all_tab_cols where owner = 'CCO'; ```
To get the DDL for all tables of the current user, you can use this: ``` select dbms_metadata.get_ddl('TABLE', table_name) from user_tables; ``` You will need to adjust your SQL client to be able to properly display the content of a `CLOB` column. More details (e.g. about how to get the DDL for other objects) can be...
How to extract table definitions using SQL or Toad
[ "", "sql", "oracle", "toad", "" ]
I have two table: ``` A: id code 1 A1 2 A1 3 B1 4 B1 5 C1 6 C1 ``` ===================== ``` B: id Aid 1 1 2 4 ``` (`B` doesn't contain the `Aid` which link to `code C1`) Let me explain the overall flow: I want to make each row in `table A` have different code(by de...
Using [`ROW_NUMBER()`](http://technet.microsoft.com/en-us/library/ms186734.aspx) inside CTE (or sub-query) you can assign numbers for each `Code` based on your ordering and then just join the result-set with your table `A` to make a delete. ``` WITH CTE AS ( SELECT A.*, ROW_NUMBER() OVER (PARTITION BY A.Code ORDE...
The first select gives you all A.id that are in B - you don't want to delete them. The second select takes A, selects all codes without an id that appears in B, and from this subset takes the maximum id. These two sets of ids are the ones you want to keep, so the delete deletes the ones not in the sets. ``` DELETE fro...
How to retain a row which is foreign key in another table and remove other duplicate rows?
[ "", "sql", "sql-server", "t-sql", "sql-delete", "duplicate-data", "" ]
Could please anyone tell me how I can return all the rows which has a maximum primary key id against each and every foreign key id. e.g. If I have an Applicant and Notes Table. Applicant table has ApplicantId as Primary key and Notes Table has NotesId as Primary key. ApplicantId is the Foreign key in Notes Table with ...
Try this: ``` SELECT ApplicantId, MAX(NotesId) FROM Notes GROUP BY ApplicantId; ``` To get the rest of the record you can do: ``` SELECT n.* FROM notes n INNER JOIN ( SELECT max(notesId) AS maxid FROM notes GROUP BY applicantId ) n2 ON n.NotesId = n2.maxid ``` `sqlfiddle demo`
``` SELECT applicantId, max(notesId) from Notes group by applicantId ```
how to get the maximum Primary key id result on the basis of each foreign key id in sql
[ "", "sql", "t-sql", "" ]
I have a table which looks like this ``` id datetime tick_info(string) 0 16-10-2013 3:33:01 "33300" 1 17-10-2013 5:04:01 "003023" 2 17-10-2013 6:12:04 "3244" 3 19-10-2013 5:32:12 "3333332" 4 20-10-2013 8:14:44 "33321" 5 20-10-2013 9:12:11 "5821" 6 22-10-2013 10:32:11 "33111" ``` And so the data can spa...
Try this:: ``` Select * from 'myTable' where 'datetime' >= ( select `datetime` from myTable group by DATE(`datetime`) order by `datetime` desc 4,1 ) ```
`SELECT * FROM yourTable WHERE tick_info>=DATE_SUB(tick_info, INTERVAL 5 DAY) group by tick_info order by tick_info DESC`
MySQL select * from last 5 days from a datetime field
[ "", "mysql", "sql", "datetime", "" ]
I'm struggling to understand why grouping by DATE on a datetime column in SQLite in Rails is returning nil. I want to return a count of users that have a value in the startdate field, grouped by date. Can anyone help? Removing the DATE aspect of the below query returns the results as I would expect. See the different ...
Closest [date formated string](http://www.sqlite.org/lang_datefunc.html) SQLite expects for your data is `YYYY-MM-DD HH:MM:SS.SSS`. If all your dates are in same timezone, `+0000`, you may ignore `DATE` function at all and compare substring: ``` User.where("startdate IS NOT NULL").group("SUBSTR(startdate,1,10)").coun...
[date()](http://www.sqlite.org/lang_datefunc.html) function expects time zone to match format "[-+]HH:MM" or "Z": ``` 2013-10-07 08:23:19.120 2013-10-07T08:23:19.120Z 2013-10-07 08:23:19.120-04:00 ```
Grouping by DATE in SQL returning nil
[ "", "sql", "ruby-on-rails", "sqlite", "date", "" ]
``` SELECT DISTINCT YEAR(convert(varchar(max),OrderCreatedDate)) from webshop ``` The above sql query is producing this error: ``` Conversion failed when converting date and/or time from character string. ``` The value in the database is NVARCHAR and in the following format: DD/MM/YYYY 00:00:00 AM (/PM) I would lik...
To avoid this sort of issues, date should be saved in DateTime type field Not in a string field. `Year()` function parameter is a `DateTime type` *not* a `String`. So you should make sure that the string you are passing is convertible to a DateTime type. In this case you could trim out the time part with `Left() funct...
``` select distinct year(CONVERT(NVARCHAR(255),CONVERT(SMALLDATETIME, columnName,105))) ```
Convert NVARCHAR to DATETIME and select distinct Year
[ "", "sql", "sql-server", "" ]
I have an application where users's activity will be rewarded with points. There will be a points chart that will assign a certain amount of points for certain action. My question is which approach is better and most importantly why? **Approach 1**: - create a userPoints table in mysql and insert points there at each...
You'll want to store: 1. **Actions** - A table listing actions and the points defined for each. This will act as your domain table. 2. **User Actions** - A composite-key table (user\_id, action\_id) listing the actions the user completed AND the points they were awarded (you'll want to store this here in case an actio...
I recommend a hybrid approach. If you strictly store points in the table, it will be very easy to lose track of who has which points for what reason. Alternatively, recalculating them constantly will bring down your server in no time if your user base grows. If you instead, recalculate points every 5 minutes, 1 hour, 1...
Storing stats in the DB or computing them at runtime?
[ "", "mysql", "sql", "" ]
I'm having trouble getting my head around this. I'm using MS SQL 2008 and I have a table for example called Activity, with 3 fields: customer (a customer's identity), visitDate (a the date that they visited) and customerType (what type of cutomer they are). Here's 3 days' of data: ``` customer visitDate ...
The slightly tricky bit is to only count a customer once for a given day and type, even if they have multiple records for that day: ``` select visitDate, sum(case when customerType = 'A' then 1 else 0 end) as TypeA, sum(case when customerType = 'B' then 1 else 0 end) as TypeB, count(*) as Total from ( ...
``` select visitDate, sum(case when customerType = 'A' then 1 else 0 end) as TypeA, sum(case when customerType = 'B' then 1 else 0 end) as TypeB, count(*) as Total from activity group by visitDate ```
Grouping by day then count result for each day
[ "", "sql", "sql-server-2008", "group-by", "" ]
This my table with sample data. ``` id | path | category (1-6) | secter_id | date ---------------------------------------------- 1 | ddd | 5 | a | 10-01 2 | ddgg | 6 | a | 10-03 3 | fff | 5 | a | 10-02 ``` I want to filter the latest category 5 and ...
This query should do it for you ``` SELECT A.ID, A.PATH, A.CATEGORY, A.SECTOR_ID, A.dDATE FROM yourTable A INNER JOIN (SELECT CATEGORY, MAX(dDate) AS dDate FROM yourTable GROUP BY CATEGORY) B ON A.CATEGORY = B.CATEGORY AND A.dDate = B.dDate ``` Here is a [SQLFiddle...
You can try with this code, is not elegant but it should work. ``` Select id,path,category,secter_id,date FROM myTable a INNER JOIN (SELECT category, MAX(date) date FROM myTable GROUP BY Category) b ON a.category = b.Category AND a.date = b.Date WHERE A.Category IN (5,6) ```
make a select query with group by
[ "", "sql", "oracle", "select", "" ]
I'm trying to figure out a query which show the **number** (amount) of employees who worked in more than 1 departments. Here the table name and fields: * `Employee`(id\_employee, employee\_name, salary) * `Department`(id\_dept, dept\_name, budget) * `Department_Employee`(id\_employee, id\_dept, workhours\_percentage) ...
``` SELECT COUNT(*) FROM ( SELECT id_employee, COUNT(*) AS CNT FROM Department_Employee GROUP BY id_employee ) AS T WHERE CNT > 1 ```
To get all employees that work in more than one department: ``` SELECT id_employee, COUNT(*) FROM Department_Employee GROUP BY id_employee HAVING COUNT(*)>1 ``` To count them: ``` ; WITH cte As ( SELECT id_employee FROM Department_Employee GROUP BY id_employee HAVING COUNT(*)>1 ) SELECT COUNT(*) FROM...
Get number of employees who worked in more than one department with SQL query
[ "", "sql", "sql-server", "t-sql", "" ]
I have the following tables - simplified quite a bit ``` Table - Tests Test A B C D E F G H Table - TestHistory Test Result Version A Pass 1 A Fail 2 B Pass 2 C Fail 1 C Pass 2 D Fail 1 D Fail 2 E Fail 1 ``` I want to get t...
I can't syntax check this, but it should be close: ``` SELECT th.Test, th.Result, th.Version FROM TestHistory th INNER JOIN ( SELECT MAX(Version) as MaxVersion, Test FROM TestHistory GROUP BY Test ) sub ON sub.MaxVersion = th.Version AND sub.Test = th.Test WH...
Small correction can be added to the above solution. In case when You need to receive the results in the Test order, the query can be transformed as below: ``` SELECT src.Test, src.Result, src.Version FROM ( SELECT th.Version, th.Test, th.Result, ROW_NUMBER() over(partition by th.Test order by th.Version...
SQL query - how do I restrict to the rows I'm interested in
[ "", "sql", "t-sql", "inner-join", "" ]
I have a table that looks like this caller 'makerar' | cname | wmname | avg | | --- | --- | --- | | canada | zoro | 2.0000000000000000 | | spain | luffy | 1.00000000000000000000 | | spain | usopp | 5.0000000000000000 | And I want to select the maximum avg for each cname. ``` SELECT cname, wmname, MAX(avg) FROM make...
Yes, this is a common aggregation problem. Before [SQL3 (1999)](http://web.cecs.pdx.edu/~len/sql1999.pdf), the selected fields must appear in the `GROUP BY` clause[\*]. To workaround this issue, you must calculate the aggregate in a sub-query and then join it with itself to get the additional columns you'd need to sho...
In Postgres, you can also use the special **[`DISTINCT ON (expression)`](http://www.postgresql.org/docs/9.3/static/sql-select.html#SQL-DISTINCT)** syntax: ``` SELECT DISTINCT ON (cname) cname, wmname, avg FROM makerar ORDER BY cname, avg DESC ; ```
must appear in the GROUP BY clause or be used in an aggregate function
[ "", "sql", "group-by", "aggregate-functions", "postgresql-9.1", "" ]
I have 4 different tables which store different transactions for users and I would like to union all of the transactions for some specific users. But the problem is, all these 4 tables have huge amount of data, therefore when I try to UNION all of them and JOIN with the users, it takes hours to compute. What I'm doing ...
Either select the "*user.state = 1 AND user.friends > 1 AND user.loc = 'Turkey'*" from your users using a [Common Table Expression](http://technet.microsoft.com/en-us/library/ms190766%28v=SQL.105%29.aspx) or into a temporary table. Then use that result in your Union.
You might try something like this: ``` SELECT blablabla FROM transactions1 t1, transactions2 t2,transactions3 t3,transactions4 t4 JOIN users ON (users.id = t1.user_id OR users.id = t2.user_id OR users.id = t3.user_id OR users.id = t4.user_id AND user.state = 1 AND user.friends > 1 AND user.loc = 'Turkey'); ```
SQL - Join one subquery for multiple times within union
[ "", "sql", "performance", "subquery", "union", "" ]
I'm using this query to delete unique records from one table. ``` DELETE FROM TABLE 1 WHERE ID NOT IN (SELECT ID form TABLE 2) ``` But the problem is that both the tables have millions of records and using subquery will be very slow. Can anyone tell me any alternative.
``` Delete t1 from table_1 t1 left join table_2 t2 on t1.id = t2.id where t2.id is null ```
SubQuery are really slow infact [joins](http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html) exists! ``` DELETE table1 FROM table1 LEFT JOIN table2 ON table1.id = table2.id WHERE table2.id is null ```
SUbstiute for SubQuery to delete records from table
[ "", "mysql", "sql", "database", "oracle", "" ]
I have a SQL query which used to cause a > Divide By Zero exception I've wrapped it in a `CASE` statement to stop this from happening. Is there a simpler way of doing this? **Here's my code:** ``` Percentage = CASE WHEN AttTotal <> 0 THEN (ClubTotal/AttTotal) * 100 ELSE 0 END ```
A nicer way of doing this is to use [NULLIF](http://technet.microsoft.com/en-us/library/ms177562.aspx) like this: ``` Percentage = 100 * ClubTotal / NULLIF(AttTotal, 0) ```
I'm using `NULLIF` bit differently, because in some cases I do have to return some value. Usually I need to return 0 when there is a divide by zero error. In that case I wrap whole expression in `ISNULL`. So it would be: ``` Percentage = ISNULL(100 * ClubTotal / NULLIF(AttTotal, 0), 0) ``` The inner part is evaluate...
Simple way to prevent a Divide By Zero error in SQL
[ "", "sql", "sql-server-2008", "t-sql", "sql-server-2005", "" ]
I am fiddling with MS SQL and I am getting different results after running these two queries (...maybe it is just my amateurism in MS SQL): /\* If you spot any syntax errors it doesn't matter, I am writing this out of my head \*/ --- ``` SELECT AVG(X.AvgDailyExpense) AS AverageDailyExpense FROM (SELECT ...
These queries will return different results because they are answering different questions. The second query answers "what is the average daily expense across all daily expense reports". The first query first finds the average daily expense by individual and then asks "what is the average of the individual-based averag...
Suppose that you have workers with the following expenses: ``` A: 1, 2, 3, 4, 5, 6, 7, 8, 9 (average 45 / 9 = 5) B: 12, 13, 14 (average 39 / 3 = 13) ``` The straight average of all the expenses is (45 + 39) / 12 = 7, but the average of the averages of the two workers is (5 + 13) / 2 = 9.
MS SQL - AVG() returns different result than AVG(AVG() with group)
[ "", "sql", "sql-server", "aggregate-functions", "average", "" ]
I have a list like this thing1,thing2,thing3. And I want to insert them into a look-up table with the same foreign key. So ideally it would look like this: ``` <cfquery datasource="#ds#" result="insert_things"> INSERT INTO lkp_things (foreign_key, thing) VALUES (1, thing1), (1, thing2), (1, thing3) </cfquery> ...
**Update:** Ultimately the real problem here was that the feature of inserting multiple sets of values with a single `VALUES` clause is only supported in SQL Server 2008+ and the OP is using 2000. So they went with the [select / union all approach](https://stackoverflow.com/a/19596550/104223) instead. --- (Expanded ...
I would add a counter and increment it inside the loop. Also you need to use `listLen()` rather than `len` on your list to get the number of items. ``` <cfquery datasource="#ds#" result="insert_things"> INSERT INTO lkp_things (foreign_key, thing) VALUES <cfset count = 1> <cfloop list="#things#" index="thing"> ...
ColdFusion: How to insert a list with a static foreign key in one insert?
[ "", "sql", "sql-server", "coldfusion", "" ]
I have a query I am trying to write in SQL Server 2008 to produce a row like this: ``` quoteID | dateEntered | insuredName | agentName | quoteType | status | noteDate | userType ``` I currently have: ``` SELECT t1.quoteID, t1.dateEntered, t1.insuredFirstName + ' ' + t1.insuredLastName as insuredName, ...
``` WITH note AS ( SELECT quoteID , dateEntered as noteDate , usertype , ROW_NUMBER() OVER (PARTITION BY quoteID ORDER BY dateEntered DESC) as row_num FROM quote_notes ) SELECT t1.quoteID, t1.dateEntered, t1.insuredFirstName + ' ' + t1.insuredLastName as insuredName, t2...
Answer to question 2: if you want a row returned always you should use a LEFT OUTER JOIN, rather than an INNER JOIN. See Wikipedia for an explanation on join types: <http://en.wikipedia.org/wiki/Join_(SQL)> As for the questions on usertype: we'll need more information about the database schema then. BTW I would advice...
How to combine 4 tables with joins and max
[ "", "sql", "sql-server", "t-sql", "join", "" ]
I just started learning PL/SQL and I'm not sure how to create a procedure. The logic seems about right but I think there's some syntactical mistake in the first line. Here's my code:- ``` CREATE OR REPLACE PROCEDURE ReverseOf(input IN varchar2(50)) IS DECLARE reverse varchar2(50); BEGIN FOR i in rever...
Two things - you shouldn't specify the datatype size in procedure's/function's parameter list and you do not need the `DECLARE` keyword. Try this: ``` CREATE OR REPLACE PROCEDURE ReverseOf(input IN varchar2) IS rev varchar2(50):=''; BEGIN FOR i in reverse 1..length(input) LOOP rev := re...
Try it without PL/SQL! ``` WITH params AS (SELECT 'supercalifragilisticexpialidocious' phrase FROM dual), WordReverse (inpt, outpt) AS (SELECT phrase inpt, CAST(NULL AS varchar2(4000)) outpt FROM params UNION ALL SELECT substr(inpt,2,LENGTH(inpt)-1), substr(inpt,1,1) || outpt FROM wordReverse WHERE LEN...
A procedure to Reverse a String in PL/SQL
[ "", "sql", "oracle", "plsql", "syntax-error", "" ]
I have a Salesman table and a Sales table, I need to get a count of Salesman whose revenue was $1,000,000 based on previous quarter. The problem I am having is this: I can do a select of the Sales Table which gets every salesman, then an inner select statement where I take each salesman and find all of his sales. I n...
There is a function sum(some\_column) in sql. Try something like this: ``` sum(select cost from sales where salesman_ID = @id) >= 1000000 ```
I think you can try SUM() function ``` SELECT SUM(column_name) FROM table_name; ``` this can get you the total sum of a numeric column. I think this will help
How to do calculations inside sql query
[ "", "sql", "pervasive", "pervasive-sql", "" ]
I have a MySQL query like so: ``` SELECT `contact_last_name` FROM `customer` WHERE `contact_last_name` IS NOT NULL ``` Basically I want to return any rows where the column `contact_last_name` has something entered in it. If it makes any difference, this column is a VARCHAR column. But instead, it is returning every ...
`NULL` requires the column to actually be `NULL`. Not an empty string. Are you trying to check if it's empty? ``` SELECT `contact_last_name` FROM `customer` WHERE `contact_last_name` != '' ``` Do you have white space issues? ``` SELECT `contact_last_name` FROM `customer` WHERE TRIM(...
There's a difference between a varchar being an empty string and it being explicitly NULL. You could try this where clause: ``` LENGTH(contact_last_name) > 0; ```
Returning results that are not null in MySQL
[ "", "mysql", "sql", "select", "" ]
I have the following models ``` class User attr_accesible :first_name, :phone_number has_one :user_extension end class UserExtension attr_accessible :company, :user_id belongs_to :user end ``` I have table which contains all users. And I need to sort this table by first\_name, phone\_number, company. With fi...
Try this: ``` @users = User.includes(:user_extension).order("user_extensions.company desc") ``` I think you need at `order`: `user_extensions`, not `user_extension`
Merge can make the query smaller/saner-looking, and it benchmarked faster for me in Rails 4.x: ``` @users = User.joins(:user_extension).merge(UserExtension.order(company: :desc)) ```
Rails order by association field
[ "", "sql", "ruby-on-rails", "postgresql", "" ]
i'm very new to SQL and don't know what is wrong with my query. plz guide I have 2 tables product and product\_consumer 1 to m relation. i want to get all products and count of consumers of each product. This is what i want: ``` id: pCount item1, 2 item2, 1 ``` i have tried the following query but it only return...
Try this ``` SELECT pc.id, COUNT(pc.id) pCount FROM product AS prd JOIN product_consumer pc ON pc.id = prd.id GROUP BY pc.id ``` Let's say your schema is this: ``` CREATE TABLE product( id int, product varchar(1) ) CREATE TABLE product_consumer( id int, consumer varchar(1), pid int ) ``` if you want...
Use the [GROUP BY](http://www.w3schools.com/sql/sql_groupby.asp) Clause ``` SELECT prd.id, count(pc.id) pCount FROM product AS prd JOIN product_consumer pc ON pc.id = prd.id GROUP BY prd.id ```
Need help in making SQL query
[ "", "sql", "" ]
``` article_vote table +------------+------+ | article_id | vote | +------------+------+ | 1 | 3 | | 1 | 1 | | 1 | -1 | | 1 | -2 | +------------+------+ ``` In MySQL 5.5 I've been trying to return two results from the above table. 1. The combined value of all negative vote...
Correct something like this: ``` select article_id, sum(case when vote >0 then vote else 0 end) as postive, sum(case when vote <0 then vote else 0 end) as negative FROM article_vote GROUP BY article_id ``` Uncrear about your where condition,sorry.
Try this out: ``` SELECT SUM(if(vote > 0, vote, 0)) positive, SUM(if(vote < 0, vote, 0)) negative FROM article_vote WHERE article_id = 1 ``` Result: ``` | POSITIVE | NEGATIVE | |----------|----------| | 4 | -3 | ``` Fiddle [here](http://sqlfiddle.com/#!2/62df8/1).
MySQL: Multiple SUMS Counting Combined Values WHERE Condition
[ "", "mysql", "sql", "count", "" ]
I have two tables: Artist and Work. Artist is a relation of painters with ArtistID, FirstName and LastName. Work is a relation of their paintings with columns WorkID, Title and ArtistID. Now, my artist relation has data and I am now inserting values to Work table. WorkID is a counter, so no problems there. I want to...
Use a [DLookup Function](http://office.microsoft.com/en-us/access-help/dlookup-function-HA001228825.aspx) to retrieve the `ArtistID` value you want to insert. Notice the similarity between this `DLookup` expression and your `SELECT` statement ... ``` INSERT INTO Work (Title, ArtistID) VALUES('Toledo', DLookup("ArtistI...
Try this ``` INSERT INTO Work (Title, ArtistID) SELECT 'Toledo', ArtistID FROM Artist WHERE FirstName='Joan' ```
SQL MsAccess embedding select into INSERT statement for some specific values
[ "", "sql", "ms-access", "ms-access-2007", "sql-insert", "" ]
I am using a SQL Server database. This query: ``` SELECT * FROM table1 WHERE table1.name = 'something' AND CASE WHEN table1.date IS NULL THEN 1 = 1 ELSE table1.date >= '2013-09-24' END; ``` gives me en error: > [Error Code: 102, SQL State: S0001] Incorrect syntax near ...
Try this code: ``` select * from table1 where table1.name='something' and (table1.date is null Or table1.date >= '2013-09-24'); ```
I think this is what you want. ``` select * from table1 where table1.name = 'something' and ( table1.date is null or table1.date >= '2013-09-24' ); ``` SQL Server doesn't really have a boolean type that you can use as a result.
CASE when is null in SQL Server
[ "", "sql", "sql-server", "null", "case", "" ]
I have 3 tables to join and need some help to make it work, this is my schema: donations: ``` +--------------------+------------+ | uid | amount | date | +---------+----------+------------+ | 1 | 20 | 2013-10-10 | | 2 | 5 | 2013-10-03 | | 2 | 50 | 2013-09-25 | | ...
It seems your table's model is not right. There should be a relation between the Causes and Donations. If not when you do your joins you will get duplicated rows. For instance. Your model could look like this: Donations ``` +--------------------+------------+ | uid | amount | date | causeId +---------+...
Try this ``` SELECT CONCAT(i.username ,' ',i.first_name) `name`, SUM(tti.amount), t.cause AS tag_name FROM users i LEFT JOIN donations tti ON (tti.uid = i.id) INNER JOIN causes t ON (t.uid = tti.uid) GROUP BY i.id ``` ## [Fiddle](http://sqlfiddle.com/#!2/0e06c/20)
mysql join 3 tables by id
[ "", "mysql", "sql", "" ]
need some help to build a query, this is my current scheme: ``` users: +----+------------+ | id | username | +----+------------+ | 1 | rob | | 2 | john | | 3 | jane | <--- jane never has donated | 4 | mike | +----+------------+ donations: +--------------------+------------+ | uid |...
For this we need to filter the data on the select and not on the join. Remove this condition: ``` AND (month(d.date), year(d.date)) = (month(CURDATE()), year(CURDATE())) ``` and add this to the select: ``` SUM (CASE WHEN (month(d.date), year(d.date)) = (month(CURDATE()), year(CURDATE())) THEN 1 ELSE 0 END) as month...
For me the easiest way to think about the separately grouped information is to put it into separate queries and then just join the results back together. This is not likely to be the most efficient, but it helps to get something working. ``` select auo.id, auo.username, coalesce(monthly_count, 0), coalesce(monthly_...
sum two rows and order by date / total
[ "", "mysql", "sql", "gaps-and-islands", "" ]
How do I use sql to get the whole month name in sql server? I did't find a way using `DATEPART(mm, mydate)` or `CONVERT(VARCHAR(12), CreatedFor, 107)`. Basically I need in the format: *April 1 2009*.
``` SELECT DATENAME(MONTH, GETDATE()) + RIGHT(CONVERT(VARCHAR(12), GETDATE(), 107), 9) AS [Month DD, YYYY] ``` OR Date without Comma Between date and year, you can use the following ``` SELECT DATENAME(MONTH, GETDATE()) + ' ' + CAST(DAY(GETDATE()) AS VARCHAR(2)) + ' ' + CAST(YEAR(GETDATE()) AS VA...
If you are using SQL Server 2012 or later, you can use: ``` SELECT FORMAT(MyDate, 'MMMM dd yyyy') ``` You can [view the documentation](https://msdn.microsoft.com/en-gb/library/hh213505(v=sql.110).aspx) for more information on the format.
sql server Get the FULL month name from a date
[ "", "sql", "sql-server", "date-conversion", "" ]
I want to know about the storage SQL Server data types in memory. How is the `money` data type in SQL Server stored in memory? I know that `money` is stored in 8 bytes and `smallmoney` is stored in 4 bytes. But I don't know how? For example when you have 123400.93 for the money, how is it stored in 8 bytes? I have t...
Just adding a bit here... A single `byte` is made up of 8 `bits`. A `bit` can hold 2 values (0 or 1). So 4 bytes is 32 bits (4 x 8). Which means the numeric range of what can be stored is from 0 to 2^32 which gives a total range of 4,294,967,296 values. `smallmoney` is signed so we drop one of the bits to be used fo...
> How are the "money" [...] data types in SQL Server stored in > memory? If you want to see how is stored a MONEY (8 bytes) value then you could execute following script step/step: ``` CREATE DATABASE TestMoneyDT; GO USE TestMoneyDT; GO CREATE TABLE dbo.MyMoney -- :-) ( Col1 CHAR(5) NOT NULL, Col2 MONEY NOT ...
How are the "money" and "decimal" data types in SQL Server stored in memory?
[ "", "sql", "sql-server", "memory", "" ]
maybe I miss something stupid but... I have three tables in m-to-m relation: ``` CREATE TABLE tbl_users ( usr_id INT NOT NULL AUTO_INCREMENT , usr_name VARCHAR( 64 ) NOT NULL DEFAULT '' , usr_surname VARCHAR( 64 ) NOT NULL DEFAULT '' , usr_pwd VARCHAR( 64 ) NOT NULL , usr_level INT(...
Because of this line: ``` where UH.user_id = 2; ``` This is only true if UH.user\_id is non-null, so it effectively excludes any case where you have a house without a matching row in UH, which is the point of using a LEFT JOIN. If you want all houses, and UH data where there is a match, use this: ``` select * from ...
Your WHERE clause is specifying that ``` UH.user_id = 2 ``` What happens if you change it to `H.user_id = 2` ? To give this (all houses for user\_id = 2): ``` select * from tbl_houses AS H left join tbl_users_houses AS UH on H.house_id = UH.house_id where H.user_id = 2; ``` Or if you want all houses regardless ...
MySQL LEFT JOIN returns empty resultset
[ "", "mysql", "sql", "" ]
The statement below is to get all non-duplicate IDs from the products table. Is there a way I can get the total count of rows that are outputted by this sql statement? ``` select min(product_id) from products where market_code = 'germany' group by product_code ``` ## sample table data: ``` product_id market_code ...
You can simply do this: ``` SELECT COUNT(*) FROM ( select min(product_id) from products where market_code = 'germany' group by product_code ) AS t; ```
Actually your query is not what you said "The statement below is to get all unique/non-duplicate IDs from the products table." , It will select lowest product\_id for product\_code , not unique , for example if there are product\_id - 2 and product\_id - 3 for product\_code A , it will only return product\_id - 2 , it ...
Is there anyway to perform a Count() when using Min()?
[ "", "mysql", "sql", "" ]
I had a very simple question: Does oracle allow multiple "WITH AS" in a single sql statement. Example: ``` WITH abc AS( select ......) WITH XYZ AS(select ....) /*This one uses "abc" multiple times*/ Select .... /*using XYZ multiple times*/ ``` I can make the query work by repeating the same query multiple times,...
You can do this as: ``` WITH abc AS( select FROM ...) , XYZ AS(select From abc ....) /*This one uses "abc" multiple times*/ Select From XYZ.... /*using abc, XYZ multiple times*/ ```
the correct syntax is - ``` with t1 as (select * from tab1 where conditions... ), t2 as (select * from tab2 where conditions... (you can access columns of t1 here as well) ) select * from t1, t2 where t1.col1=t2.col2; ```
Can we have multiple "WITH AS" in single sql - Oracle SQL
[ "", "sql", "oracle", "" ]
I am getting the error `subquery must return only one column` when I try to run the following query: ``` SELECT mat.mat as mat1, sum(stx.total) as sumtotal1, ( SELECT mat.mat as mat, sum(stx.total) as sumtotal FROM stx LEFT JOIN mat ON stx.matid = mat.matid LEFT JOIN sale ON stx.saleid = sale.i...
Put a subquery that returns multiple columns in the `FROM` list and select from it. A correlated subquery would be a bad idea to begin with. However, your query is not even correlated (no link to outer query) and seems to return multiple rows. This leads to a (possibly very expensive and nonsensical) cross join produc...
Instead of subquery select statement ``` SELECT mat.mat as mat, sum(stx.total) as sumtotal ``` Try this statement ``` SELECT sum(stx.total) as sumtotal ```
error : subquery must return only one column
[ "", "sql", "database", "postgresql", "left-join", "cross-join", "" ]
I have this problem with SQL and I can't figure it out. Imagine that I have 3 tables as follows ``` Names Nameid name 1 Starbucks Coffee 2 Johns Restaurant 3 Davids Restaurant user_likes userid Nameid 1 1 2 1 2 3 user_visited userid Name...
I've made a quick test and although I prefer Serge's solution, this one seemed to perform faster as the amount of items to join will be less: ``` SELECT n.nameId, n.name, coalesce(sum(likesCount), 0) totalCount FROM NAMES n LEFT JOIN ( SELECT nameId, count(*) likesCount FROM user_likes GROUP BY nameId UNION ALL ...
``` SELECT n.name, t.nameid, COUNT(t.nameid) AS freq FROM Names n JOIN ( SELECT nameid FROM user_likes UNION ALL SELECT nameid FROM user_visited ) t ON n.nameid = t.nameid GROUP BY t.nameid ORDER BY freq DESC ```
Find the frequency of rows from multiple joint tables
[ "", "mysql", "sql", "" ]
I have the following sql statement: ``` select a.desc ,sum(bdd.amount) from t_main c left outer join t_direct bds on (bds.repid=c.id) left outer join tm_defination def a on (a.id =bds.sId) where c.repId=1000000134 group by a.desc; ``` When I run it I get the following result: ``` des...
Your new left outer join is forcing some rows to be returned in the result set a few times due to multiple relations most likely. Remove your SUM and just review the returned rows and work out exactly which ones you require (maybe restrict it to on certain type of t\_ind record if that is applicable??), then adjust you...
If you really need to receive the data as you mentioned, your can use sub-queries to perform the needed calculations. In this case you code may looks like the following: ``` select x.[desc], x.amount, y.amt from ( select c.[desc] , sum (bdd.amount) as amount , c.id from t_main c lef...
Left outer join on multiple tables
[ "", "sql", "sql-server", "t-sql", "" ]
How do I convert the current time (datetime) in my timezone into another timezone, say France ? I looked around in SO, but did not find any posts which could help me. I am using SQL server 2008.
``` select CONVERT(datetime,SWITCHOFFSET(CONVERT(datetimeoffset,GetUTCDate()),'+05:30')) Date_India, select CONVERT(datetime,SWITCHOFFSET(CONVERT(datetimeoffset,GetUTCDate()),'+03:30')) Date_Iran ``` [check here](http://mssqlfun.com/2012/07/26/how-to-insert-datetime-with-different-timezones/)
Please replace getdate() with GetUTCDate() to get accurate result otherwise the offset (5:30) in this case will be added to the current time (which will already have some offset) and will result in incorrect result. For instance if you are in Pakistan then GetDate() will give you time as GMT+5:00 and adding 5:50 offse...
sql server convert datetime into another timezone?
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a table A which has a structure like this: ``` ID Name City zip 1 xxx wer 134 2 yyy qwe 234 3 zzz ert 256 4 www qwe 567 ``` Now i would like to update multiple rows with one SQL query. For instance Query: ``` UPDATE A SET zip= '355' WHERE id= '2'; ``` Will update one...
If you mean that you want to update multiple rows to the same zip with one query, you can use the following: ``` UPDATE A SET zip= '355' WHERE id in ('1','4'); ``` However, if you mean that you want to update multiple rows to zip values this cannot be done without some logic sitting behind which id should get w...
Please try case condition to update with different values: ``` UPDATE A SET zip=case when ID='1' then 'Value1' else 'Value2' end WHERE ID IN ('1', '4'); ```
Updating a number of row with a single SQL query in Oracle DBMS
[ "", "sql", "oracle", "sql-update", "" ]
I have a PostgreSQL database in which one table rapidly grows very large (several million rows every month or so) so I'd like to periodically archive the contents of that table into a separate table. I'm intending to use a cron job to execute a .sql file nightly to archive all rows that are older than one month into t...
Question was answered by a friend in IRC: `'now'::timestamp - '1 month'::interval` Having the timestamp return 00:00:00 wasn't terrible important, so this works for my intentions.
``` select date_trunc('day', NOW() - interval '1 month') ``` This query will return date one month ago from now and round time to 00:00:00.
Get timestamp of one month ago in PostgreSQL
[ "", "sql", "postgresql", "" ]
I have two tables with data. Both tables have a `CUSTOMER_ID` column (which is numeric). I am trying to get a list of all the unique values for `CUSTOMER_ID` *and* know whether or not the `CUSTOMER_ID` exists in both tables or just one (and which one). I can easily get a list of the unique `CUSTOMER_ID`: ``` SELECT t...
If the CUSTOMER\_ID appears in both tables then we'll have to arbitrarily pick which table to call the source. The following query uses "tblOne" as the [SourceTable] in that case: ``` SELECT CUSTOMER_ID, MIN(Source) AS SourceTable, COUNT(*) AS TableCount FROM ( SELECT DISTINCT CUSTO...
Gord Thompson's answer is correct. But, it is not necessary to do a distinct in the subqueries. And, you can return a single column with the information you are looking for: ``` select customer_id, iif(min(which) = max(which), min(which), "both") as DataSource from (select customer_id, "tblone" as which f...
Create a UNION query that identifies which table the unique data came from
[ "", "sql", "ms-access", "unique", "union", "" ]
Anyone know sql query or wordpress plugin which may help me to remove duplicate comments. While I was importing posts, comments into wordpress, i got some timeouts, and repeated process, so some of comments posted twice.
Taking a look at some of the images of WordPress' schema then you should be able to identify the records you want to delete with a query such as ``` SELECT wp_comments.* FROM wp_comments LEFT JOIN ( SELECT MIN(comment_id) comment_id FROM wp_comments GROUP BY comment_post_id, comment_author, comment_content...
Wow, this worked like a charm, a more aggressive form I used eventually to eliminate all duplicate comments regardless of author or post ID will be : ``` DELETE wp_comments FROM wp_comments LEFT JOIN ( SELECT MIN(comment_id) comment_id FROM wp_comments GROUP BY comment_content ) to_keep ON wp_comments.comm...
Remove duplicated comments in Wordpress?
[ "", "sql", "wordpress", "comments", "" ]
I want to use the id for naming the image file inside a row. Is there a way to use the id of the (current) row inside the query itself. (I know about the lastInsertId() but it works generally after the query and not inside it.) ``` INSERT INTO table (id, intro, detail, image) VALUES (null, introtext, detailtext, get_...
``` INSERT INTO table (id, intro, detail, image) SELECT id, 'introtext', 'detailtext', CONCAT('id_', id, '.jpg') FROM ( SELECT AUTO_INCREMENT AS id FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA` LIKE 'database_name' AND `TABLE_NAME` LIKE 'table') AS h ``` * **[INSERT ... SELECT](http://dev.my...
It is not possible to know what the ID will be before insertion. It's also not recommended to use this data as a real value. This column is supposed to be a transparent identifier of the row. This is useful for `JOIN`s. The fact that it can be convenient for lookups is incidental and should not be relied upon. This ID...
Is there a way to use the current row's (that is about to be inserted) id number inside query itself?
[ "", "mysql", "sql", "" ]
Taking a sample table: ``` WITH t(val) AS ( SELECT 'my Name' FROM dual UNION SELECT 'my name' FROM dual UNION SELECT 'my naim' FROM dual UNION SELECT 'MY kat' FROM dual UNION select 'my katt' from dual ) SELECT * FROM t; ``` I need an output by preference: The query s...
Just filter as you describe, then sort by that order, then grab the first record: ``` WITH t AS ( SELECT 'my Name' as val FROM dual UNION SELECT 'my name' FROM dual UNION SELECT 'my naim' FROM dual UNION SELECT 'MY kat' FROM dual UNION select 'my katt' from dual ) SELEC...
For large data sets you'd probably want to avoid the unnecessary tests if any of the earlier ones had found a match. ``` with t as ( SELECT 'my Name' as val FROM dual UNION SELECT 'my name' FROM dual UNION SELECT 'my naim' FROM dual UNION SELECT 'MY kat' FROM dual UNION select 'my katt' from...
oracle sql search by preference
[ "", "sql", "oracle", "" ]
I want to find top 2 customers with maximum orders. The table looks like: ``` CustomerId OrderId ProductId 101 1 A 101 3 B 101 4 C 102 9 D 102 9 E 103 11 E 103 22 F ``` This is the output that I need from SELECT query: ...
Here is the [**SQL Fiddle**](http://sqlfiddle.com/#!6/dcd42/5/0) example that shows the below code working: ``` SELECT DISTINCT CO.CustomerId, CO.OrderID FROM ( SELECT TOP(2) COS.CustomerId, COUNT(DISTINCT COS.orderId) as NoOfOrders FROM custorders AS COS GROUP BY COS.CustomerId ORDER BY COUNT(DISTINCT COS.or...
Try this: ``` SELECT c.CustomerId, c.OrderId FROM CustomerOrder c INNER JOIN (SELECT TOP 2 WITH TIES CustomerId, COUNT(distinct OrderId) as Count FROM CustomerOrder GROUP BY CustomerId ORDER BY Count DESC) b ON c.CustomerId = b.CustomerId ``` You could use WITH TIES, For example, if you have 3 customers with the same...
SQL Server - Find Top n customers with maximum orders
[ "", "sql", "sql-server", "join", "subquery", "inner-join", "" ]
My Table structure: **Quran Master** ![enter image description here](https://i.stack.imgur.com/nl9QF.png) QuranPrayed: ![enter image description here](https://i.stack.imgur.com/BLmGx.png) I wanted to make result according to my timestamp. Means want to get count of sipara according to timestamp. for that i made ...
try this ``` SELECT qm.sipara, Prayed = COUNT(qp.Sipara) FROM QuranMaster qm LEFT JOIN QuranPrayed qp ON (qp.sipara = qm.sipara AND qp.TimeStamp >= '2013-10-27 19:59:00.000' AND qp.TimeStamp <= '2013-10-28 20:00:00.000') GROUP BY qm.sipara,qm.OrderID ORDER BY qm.OrderID ``` basically, your WHERE claus...
Problem is that your between for timestamp is dropping the records you want to sum. Do the sum first and then do left join from the master. ``` SELECT qm.sipara , vsum.Prayed From QuranMaster qm LEFT JOIN ( Select qp.sipara , Prayed = COUNT(qp.Sipara) From QuranPrayed qp GROUP BY qp.sipara...
Not ordering all column values
[ "", "sql", "database", "sql-server-2008-r2", "" ]
I need to show the names and IDs of all artists who have not recorded titles but do have web addresses listed in my database. This invovles two tables: ``` Artists ------- ArtistID, ArtistName, City, Region, WebAddress Titles ------ TitleID, ArtistID, Title, StudioID, Genre ``` My query is as follows: ``` select ...
In MySql, null is not a value, so `where ar.webaddress != NULL;` will not work. There is special syntax for checking nulls, `is null` and `is not null` for example. Also, the inner join will only give you artists that have titles. To get artists without titles, try outer join and check for null in the joined table i.e...
Note that null is not a value so you cant mention it with equal or not equal symbol: Try this: ``` select * from artists where ar.webaddress Is not NULL and artistid not in(select distinct artistid in titles) ```
JOIN returns empty set
[ "", "mysql", "sql", "" ]
I have log table where there is are records with user id and the date for a specific activity done. I want to get names of users having activity every month. I am using the following query ``` select distinct(employeeid) from transactions where eventdate between '01-OCT-13' AND '23-OCT-13' and eventdate between '01-S...
You can use COUNT as analytical function and get the number of months for each employee and total number of months. Then select only those employees where both counts match. ``` select distinct employeeid from ( select employeeid, count(distinct trunc(eventdate,'month')) --count of months for each em...
By *very inefficient*, I think you mean *it doesn't work*. The same value can't be both in september, in october, etc. Anyway, using @LaggKing suggestion, you could try this query: ``` SELECT employeeid FROM ( SELECT DISTINCT employeeid, MONTH(eventdate) FROM transactions ) HAVING COUNT(*) = MONTH(NOW()) ``` **EDI...
Get name of person having activity in every month - Oracle SQL
[ "", "sql", "oracle", "" ]
I have the following script - ``` select sum(duration) as duration from opr where op in ('GRC','GCQ') and timestamp between '20130101000000' and '20130930235959' ``` I receive the value - **34459298** seconds. I would like to include these restrictions - The duration which is * <= '18000000' (seconds)...
Is `duration` a number or a string? Would be better to compare with numbers, I guess: ``` SELECT SUM( CASE WHEN duration <= 18000000 THEN duration * 0.14 WHEN duration > 18000000 AND duration <= 27000000 THEN duration * 0.11 WHEN duration > 27000000 THEN duration * 0.09 ELSE 0...
use subquery to select specific duration and multiply duration by your values and than use sum over that subquery.
Multiple aggregate function
[ "", "sql", "database", "plsql", "" ]
I was trying to pull the `TOTAL_PRICE` from the cart table using the the following query. Currently it will fetch the `TOTAL_PRICE` from last 30 days. But I need to modify the query to fetch the `TOTAL_PRICE` of the current month. ie, `PURCHASED_DATE` should be in between 1 to 30/31 of the current month. ``` SELECT TO...
You can use TRUNC and LAST\_DAY: ``` SELECT TOTAL_PRICE FROM CUST_CART_TABLE WHERE USER_ID = '"+userId+"' AND (TRUNC(PURCHASED_DATE) BETWEEN TRUNC(SYSDATE, 'MM') AND TRUNC(LAST_DAY(SYSDATE))); ```
You can try this one - ``` SELECT TOTAL_PRICE FROM CUST_CART_TABLE WHERE USER_ID = '"+userId+"' AND TRUNC(PURCHASED_DATE,'MONTH') = TRUNC(SYSDATE,'MONTH'); ``` It will return records from the current month.
Fetch the records from current month
[ "", "sql", "oracle", "" ]
I have a table users in it there are columns userPoints and userStatus each user begins as a newbie. if the userPoints reach 100 user status should change to something else there is another table userStatuses statusId statusName minPoints maxPoints can I create a trigger that will fire off when userPoints reach 100 ...
Try this: ``` delimiter // CREATE TRIGGER changeUserStatus BEFORE UPDATE ON users FOR EACH ROW BEGIN IF NEW.userPoints > 100 THEN SET NEW.userStatus = 'lvl2'; END IF; END;// delimiter ; ``` `delimiter` allows the user of semicolons within in the trigger definition. Of course, assumes that you hard...
You can do: ``` CREATE TRIGGER update_status BEFORE UPDATE ON users FOR EACH ROW BEGIN SET @NEWSTATUS = (SELECT statusId FROM userStatuses WHERE NEW.userPoints BETWEEN minPoints AND maxPoints); IF @NEWSTATUS != OLD.userStatus THEN SET NEW.userStatus = @...
mysql trigger to change user status after a certain amount of points has been reached
[ "", "mysql", "sql", "triggers", "" ]
I have a problem with trigger below. Thanks for any help. ``` CREATE TRIGGER upper_case ON osoba AFTER INSERT AS BEGIN DECLARE @imie VARCHAR(25) DECLARE @new_imie VARCHAR(25) DECLARE my_cursor CURSOR FAST_FORWARD FOR SELECT imie FROM INSERTED OPEN my_cursor FETCH NEXT FROM my_cursor INTO @imie ...
Don't use a cursor for this. You can use an `UPDATE` statement that affects all rows at once instead of processing them one by one. ``` CREATE TRIGGER upper_case ON osoba AFTER INSERT AS BEGIN UPDATE O SET imie = UPPER(SUBSTRING(I.imie, 1, 1)) + SUBSTRING(I.imie, 2, LEN(I.imie)) FROM INSERTED...
You should use `SET` when you assign `@new_imie` ([msdn](http://msdn.microsoft.com/en-us/library/ms189484.aspx)): ``` SET @new_imie = UPPER(SUBSTRING(@imie, 1, 1)) + SUBSTRING(@imie, 2,LEN(@imie)); ```
SQL Server : Insert trigger
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "triggers", "" ]
I'm a newbie with sql. I have this table with these records: table `mark` ``` ---------------------------------------- student_id | subject_id | comp_id | mark ---------------------------------------- 1 | 1 | 28 | 5.5 1 | 1 | 29 | 7.5 1 | 1 | 30 ...
Use `distinct` ``` SELECT distinct subject_id FROM mark WHERE student_id = 1 ``` or group the data ``` SELECT subject_id FROM mark WHERE student_id = 1 group by subject_id ```
Just use `DISTINCT`: ``` SELECT DISTINCT subject_id FROM mark WHERE student_id =1 ```
MySQL - return only 1 record for each certain id
[ "", "mysql", "sql", "" ]
I have very strange problem. I have query like this which I run in SQL server 2008 R2: ``` SELECT TOP (20) * FROM MyTable WHERE a = 0 AND b = 0 AND c = 0 ``` that uses my index on MyTable but this one doesn't: ``` SELECT TOP (20) * FROM MyTable WHERE a = 0 OR b = 0 OR c = 0 ``` and i want to execu...
You cannot use that one index for a query which has `or` between conditions. Just think about it: any one of the values can match so the index matching can't guarantee that there are no other records matching that criteria. It is really like running separate searches and then matching them together.
In order to use Index, SQL-Server checks for lot of things **1)** If the filter is SARG. **2)** Index use likelihood ratio (No of unique records : total no of records) **3)** No of records to fetch (if less records, index may be used or else table scan. Because sql-server finds it easy to scan the whole table than t...
why my query is not sargable
[ "", "sql", "sql-server", "performance", "sql-server-2008-r2", "" ]
I have a stored procedure in a package in an Oracle database that has 2 input parameters + 1 output CLOB parameter. How do I view the output in Toad? (Preferably with the user only having execute/select permissions) **Solution:** ``` DECLARE my_output_parameter CLOB; BEGIN my_package.my_stored_proc(1, 2, my_ou...
I guess DBMS\_OUTPUT.PUT\_LINE has an internal line limit of 255 chars. However it has been removed from 10g Release 2 onwards. You can try inserting the column data in a table and view it later on by querying that table. Please refer - <http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:146412348066...
Would you consider printing the `CLOB` as a result set? You could then use a `PIPELINED` function (more about them here: [PIPELINED functions by Tim Hall](http://www.oracle-base.com/articles/misc/pipelined-table-functions.php)) which would return the `CLOB` line by line, take a look at the example below: ``` CREATE TA...
How do I view a CLOB output parameter in TOAD from an Oracle Stored Procedure?
[ "", "sql", "oracle", "stored-procedures", "toad", "clob", "" ]
Is there a function in apache PIG that's similar to Lead/Lag function in SQL? Or any pig function that can look back to previous row of record?
Here is an alternative: ``` import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.FrontendException; import o...
Yes, there is pre-defined functionality. See the [Over()](http://pig.apache.org/docs/r0.12.0/api/org/apache/pig/piggybank/evaluation/Over.html) and [Stitch()](http://pig.apache.org/docs/r0.12.0/api/org/apache/pig/piggybank/evaluation/Stitch.html) methods in Piggybank. Over() has examples listed in the documentation.
lead/lag function in apache PIG
[ "", "sql", "apache-pig", "" ]
I have a problem where when getting the results of a query on the product\_view table I would also like to get the total number of product months (from the product\_month column) for each month related in the query results. ## For example If I did a query like this: ``` SELECT * FROM product_view WHERE product_price...
You can use GROUP BY product\_month: ``` SELECT product_month, COUNT(*) FROM product_view WHERE product_price BETWEEN 945 AND 980 GROUP BY product_month; ``` `sqlfiddle demo` This will give you: ``` PRODUCT_MONTH COUNT(*) AUG 1 FEB 2 JAN 2 JUL 1 JUN ...
I think you should use query below: ``` SELECT PRODUCT_ID, PRODUCT_MONTH, PRODUCT_PRICE, COUNT(*) FROM product_view WHERE product_price BETWEEN 945 AND 980 GROUP BY PRODUCT_ID, PRODUCT_MONTH, PRODUCT_PRICE; ```
Getting the count() of a column from a resulting query?
[ "", "mysql", "sql", "" ]
I need to update table using join and limit. I construct this query ``` UPDATE table1 JOIN table2 AS b ON table1.id = b.id SET table1.username = b.post_username WHERE b.post_username != '' AND table1.username = '' LIMIT 10 ``` unfortunaetly I recive error: ``` Error Code: 1221 Incorrect usage of UPDATE and LIMIT ``...
I'm afraid you can't do that: If you read the [documentation](http://dev.mysql.com/doc/refman/5.0/en/update.html) it says: > With no WHERE clause, all rows are updated. If the ORDER BY clause is > specified, the rows are updated in the order that is specified. The > LIMIT clause places a limit on the number of rows t...
hey just Delete `LIMIT 10` from your code
Mysql Update wtih Join and limit
[ "", "mysql", "sql", "join", "" ]
I have a table in MySQL as follows. ``` studentId studentName status ``` Here studentId is the ID of the student ,name is his/her name and status is pass/fail. I need a MySQL query to return the top N rows based on the condition that the student has passed. For instance ,if the table contains ``` 0001 Sam Pass 1...
You can do: ``` SELECT * FROM yourTable WHERE `status` = "Pass" LIMIT 3; ``` From the [docs](http://dev.mysql.com/doc/refman/5.1/en/select.html): > The LIMIT clause can be used to constrain the number of rows returned > by the SELECT statement. LIMIT takes one or two numeric arguments, > which must both be nonnegati...
Use `limit` :: **n** is the number of rows you want ``` Select * from student limit n ```
Need a query to get top N rows from MySQL database based on a condition
[ "", "mysql", "sql", "" ]
i am using an oracle database, i have two tables. table A primary key = productid table B references productid of table A primary key = imageid flow: each product should have 4 images stored in the table B (mandatory) problem: there are some products that has only 2 or sometimes 3 or sometimes 1 image only despi...
``` SELECT Count(DISTINCT TableA.productid) FROM TableA JOIN TableB ON TableA.productid = TableB.productid; ```
Do a sub query with where exists ``` select count(*) from tableA where exists (select 1 from tableB where tableA.productid = tableB.productid) ```
how to select only 1 unique data when joining two tables, if the table structure is one to many?
[ "", "sql", "oracle", "" ]
We have 3 different tables ie. users, daily\_status, status\_types fields in tables user : ``` id, name, department_id ``` data for user table: ``` u1 jai 1 u2 singh 1 u3 test 2 ``` daily\_status: ``` id, user_id, status_id, date ``` data for daily\_status table: ``` 1 u1 2 '23/10/2013' 2 u1 3 '24/10/2013' 3 u...
Move the date validation to the ON: ``` SELECT u.id, u.name, status.status_name FROM user u LEFT JOIN daily_status as ds ON u.id=ds.user_id AND ds.date='24/10/2013' LEFT JOIN status_types as status ON ds.status_id=status.id WHERE u.department_id=1 ``` `sqlfiddle demo`
Maybe I'm over simplifying this but you only have one record that has the given date 24/10/2013 so only one can show. If you have more than one listing for a person on a given date you could do something like this ``` SELECT a.id,a.[name],status_types.status_name FROM(SELECT id,[user].[name],department_id,ROW_NUMBER(...
how to make custom query from multiple tables
[ "", "mysql", "sql", "left-join", "" ]
I had a problem come through concerning missing data on Oracle 12c. I took a look at the code and found a query that works on mysql, mssql, oracle 11g, but has different behaviour in oracle 12c. I have generalized the table structure and query somewhat and reproduced the issue. ``` create table thing (thing_id numbe...
**UPDATE:** This is fixed in 12.1.0.2. --- This definitely looks like a bug in 12.1.0.1. I would encourage you to create a service request through Oracle support. They might be able to find a fix or a better work around. And hopefully Oracle can fix it in a future version for everyone. Normally the worst part about w...
Refer to: ANSI Outer Join Query Returns Wrong Results After Upgrade to 12.1.0.1 (Doc ID 1957943.1) Unpublished bug 16726638 Fixed in 12.1.0.2 (I have tested this) Workaround (I tested in 12.1.0.1): ``` alter session set "_optimizer_ansi_rearchitecture"=false; ``` Note 1957943.1 recommends as an alternative: ``` ...
Query featuring outer joins behaves differently in Oracle 12c
[ "", "sql", "oracle", "oracle12c", "" ]
I have googled and haven't found any that matches my case. ``` declare @from_ datetime, @to_ datetime SET @from_ = '2013-01-01' SET @to_ = '2013-10-01' DECLARE @query NVARCHAR(4000) SET @query = N' DECLARE @from datetime, @to datetime SET @from = CAST('''+@from_+''' AS datetime) SET @to = CAST('''+@to_+''' AS date...
Your problem is that you are adding a datetime with a varchar. Try this instead: ``` declare @from_ char(8), @to_ char(8) SET @from_ = '20130101' SET @to_ = '20131001' DECLARE @query NVARCHAR(4000) SET @query = N' DECLARE @from datetime, @to datetime SET @from = CAST('''+@from_+''' AS datetime) SET @to = CAST('''+...
I am not sure but I guess you have appended apostrophe(') to `@from_` and to `@to_` ``` SET @from = CAST('''+@from_+''' AS datetime) SET @to = CAST('''+@to_+''' AS datetime) ``` Also why are you not directly setting the values like this ``` SET @from = @from_ SET @to = @to_ ```
Conversion failed when converting date
[ "", "sql", "sql-server-2008", "" ]
Using SQL Server 2012. I want to insert unique strings into a table. I always want to return the row ID of the unique string. Now, this can be accomplished in two ways. **Which solution is the best?** This is the table in question: ``` CREATE TABLE [dbo].[Comment]( [CommentID] [int] IDENTITY(1,1) NOT NULL, [...
In my testing I have found that it is much more efficient to check for the violation first instead of letting SQL Server try and fail, especially when the failure rate is expected to be significant (and at best they perform about the same overall, when the failure rate is low). Details [here](http://www.mssqltips.com/s...
Personally I do it like this ``` INSERT INTO [dbo].[Comment]([Comment]) SELECT T.Comment FROM (SELECT @Comment) T (Comment) LEFT JOIN dbo.Comment C ON C.Comment = T.Comment WHERE C.Comment IS NULL SELECT @CommentID = CommentID FROM dbo.Comment C WHERE C.Comment = @Comment ```
Duplicate check using SELECT or rely on unique index?
[ "", "sql", "sql-server", "" ]
Let's say I have screen where user select different options to sort data in a grid given below the data is fetched asynchronously through jQuery from database. When user selects he needs to view `user` data where `status=1` ``` SELECT * FROM user WHERE status=1; ``` And same for 2, 3, 4 a variable can be passed. Bu...
``` SELECT * FROM user WHERE @status is null Or status = @status ```
Use ISNULL() or COALESCE() function. Pass NULL value in parameter for all records and write query like ``` SELECT * FROM user WHERE status=ISNULL(@status,status) ``` **UPDATE :** Above query will not returns null records, so if your table have null records then you need to write query as Kaf mentioned like ``` SELEC...
A keyword to specify in WHERE clause to get all the data without filtering the field
[ "", "sql", "sql-server", "t-sql", "" ]
I need the amount of words that start from all the characters of the alphabet, exist in my database I tried the following query: ``` SELECT COUNT(id) FROM(SELECT id FROM words WHERE word LIKE 'A%') as A, COUNT(id) FROM(SELECT id FROM words WHERE word LIKE 'B%') AS B, ... COUNT(id) FROM(SELECT id FROM...
USE CASE WHEN AS FOLLOWS ``` SELECT COUNT(CASE WHEN word LIKE 'A%' THEN 1 END) AS A ,COUNT(CASE WHEN word LIKE 'B%' THEN 1 END) AS B ......... ,COUNT(CASE WHEN word LIKE 'Z%' THEN 1 END) AS Z FROM WORDS ```
I'd suggest sub-stringing out the first character: ``` select substring(word,1,1) as firstChar, count(id) from... group by substring(word,1,1) ``` That seems easier than 26 individual checks.
Count results with condition in the select part of the query
[ "", "sql", "sql-server", "" ]
I have a query optimization problem. Let's say there is a table which has all the invoices. Using a TVP (Table Valued Parameter) I'd like to select few records by providing 1..n ids, or return all records by providing a single id with the value of -1. ``` DECLARE @InvoiceIdSet AS dbo.TBIGINT; INSERT INTO @Invo...
I am going to accept my own answer here: ``` DECLARE @InvoiceIdSet AS TBIGINT --INSERT INTO @InvoiceIdSet --VALUES ( 1 ), -- ( 2 ), -- ( 3 ), -- ( 4 ) INSERT INTO @InvoiceIdSet VALUES ( -1 ) SELECT TOP 100 I.Id , Number , DueDate , IssuedDate , Amount ,...
If `or S.ID=-1` is added, the SQL Server knows that the condition is true for each row; therefore, the query plan will use Scan as in your second plan. As Martin Smith says in the comment, the SQL Server isn't clever enough in this situation. You need to either have 2 queries (one if -1 is there, other if only some row...
Efficient way to select few or all records from a table
[ "", "sql", "sql-server", "" ]
``` describe table_name ``` doesn't show the constraints, Is there a way to do that?
Use the DBMS\_METADATA package, as [explained here](http://asktom.oracle.com/pls/asktom/f?p=100:11:0%3a%3a%3a%3aP11_QUESTION_ID:1794096300346327738).
You can use system views. E.g. user\_\* or all\_tab\_columns and all\_cons\_columns. Try like this: ``` SELECT tc.column_id, tc.table_name, tc.column_name, tc.data_type, cc.constraint_name FROM user_tab_columns tc, user_cons_columns cc WHERE tc.table_name = cc.table_name(+) AND tc.column_name = cc.column...
How to show the schema of a table include the constraints in Oracle?
[ "", "sql", "oracle", "" ]
I need some help using the SQL `max` and `sum` aggregate functions in SQL. I want to display the first and last names of employees who have put in the most number of total hours on projects. And I want to list the employees with the highest total combined project hours. I have two tables: ``` employee: FNAMEM--LNAM...
You need to use a group by if you are going to use the aggregate function `sum`. Something like this; ``` SELECT s.fname, s.lname FROM (SELECT fname, lname, SUM(w.hours) SumHours, w.project_num FROM Emplyee e JOIN Works_on w ON w.essn = e.ssn GROUP BY e.fname, e.lname, w.project_num) s WHERE s....
``` SELECT s.fname, s.lname FROM (SELECT fname, lname, SUM(w.hours) SumHours FROM employee e JOIN works_on w ON w.essn = e.ssn GROUP BY e.fname, e.lname) s WHERE s.SumHours = (SELECT MAX(hours) MaxSum FROM works_on w1); ``` This code worked for me; Thanks to user: PM 77-1 for ...
How to use SQL MAX(SUM()) function
[ "", "sql", "sum", "max", "sqlplus", "" ]
I am trying to construct an SQL query that would take a set of rows and renumber a field on all rows, starting at where they all match a session ID. e.g. before change: ``` SessionID | LineNumber | LineContents ---------------------------------------------- 74666 | 1 | example content 74666 |...
Using `Row_Number()` function and `CTE`: ``` ;WITH CTE AS ( SELECT SessionID, LineNumber, LineContents, Row_Number() OVER(PARTITION BY SessionID ORDER BY LineNumber) Rn FROM Table1 ) UPDATE CTE SET LineNumber = Rn WHERE SessionID = 74666; ``` **[Fiddle Demo](http://sqlfiddle.com/#!3/3c3466/1)**
You can use ROW\_NUMBER ( MS SQL ) or ROWNUM ( Oracle ) or similar inside your UPDATE statement. [Check this](https://stackoverflow.com/questions/13648898/sql-update-with-row-number) [Or this](https://stackoverflow.com/questions/12390612/how-to-assign-row-number-to-a-column)
Updating fields in sql incrementing by 1 each time
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
In SQL Server 2008 R2, suppose I have a table layout like this... ``` +----------+---------+-------------+ | UniqueID | GroupID | Title | +----------+---------+-------------+ | 1 | 1 | TEST 1 | | 2 | 1 | TEST 2 | | 3 | 3 | TEST 3 | | 4 | 3 | TEST...
With SQL-Server as rdbms you can use a ranking function like `ROW_NUMBER`: ``` WITH CTE AS ( SELECT UniqueID, GroupID, Title, RN = ROW_NUMBER() OVER (PARTITON BY GroupID ORDER BY UniqueID DESC) FROM dbo.TableName ) SELECT UniqueID, GroupID, Title FROM CTE WHERE RN = 1 ``` ...
``` SELECT * FROM (SELECT uniqueid, groupid, title, Row_number() OVER ( partition BY groupid ORDER BY uniqueid DESC) AS rn FROM table) a WHERE a.rn = 1 ```
Selecting row with highest ID based on another column
[ "", "sql", "sql-server-2008", "greatest-n-per-group", "" ]
On occasion, I'm interested in getting a list of columns in one of the tables or views in my SQL Server 2008 R2 database. It's useful, for example, if you're building database documentation without using an expensive off-the-shelf product. What's an easy way to get this information?
In SQL Server 2008 R2 (among other versions), there are system views provided automatically with every database. As long as you are connected to the database where your table resides, you can run a query like this: ``` DECLARE @TableViewName NVARCHAR(128) SET @TableViewName=N'MyTableName' SELECT b.name AS ColumnName,...
Another way is querying the INFORMATION\_SCHEMA.columns view as detailed here: [Information\_Schema - COLUMNS](http://technet.microsoft.com/en-us/library/ms188348.aspx) This will give you information for all the columns in the current database (and what table/view they belong to) including their datatypes, precision,...
How do I get a list of columns in a table or view?
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2008-r2", "" ]