Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a table ``` Name Description EID name1 ssdad 1001 name2 gfd 1002 name3 gfdsffsdf 1003 name4 ssdad 1004 name5 gfd 1005 name6 gfdsffsdf 1006 ``` i want to append **C** letter for EID's 1001,1002,1003 only. How to ...
Since you're targeting only 3 values, you could include them in a list. ``` SELECT EID, IIf(EID In ('1001','1002','1003'), 'C', '') & EID AS adjusted_EID FROM YourTable; ``` If you actually want to change the stored values, you can use that list in the `WHERE` clause of an `UPDATE`. ``` UPDATE YourTable SET ...
You can use IIF to check a condition and then do something accordingly. In your case, you can check if `EID` is less than 1004, and append 'C' to the result if it is. So if you want to only select, query will be: ``` select name, description, IIF(val(EID) < 1004, "C" & EID, EID) from yourtable ``` If you are updatin...
How to append a letter in column values access sql
[ "", "sql", "ms-access", "" ]
I have a table named studios with the columns "earnings" and "country". Each item of that table describes a studio in a country and its earnings. How can I select the average earnings of the studios for each country? ``` SELECT AVG(earnings) --I want per country FROM studios ```
``` SELECT country,AVG(earnings) FROM studios GROUP BY country; ```
You can do that: `"SELECT AVG(earnings) FROM studios GROUP BY country"` If you have column country\_id is for prefer. You can use and this query `"SELECT AVG(earnings),country FROM studios GROUP BY country"`
How to select avg(value) per column_name in sql
[ "", "sql", "group-by", "average", "" ]
I have two models, `Recipes` and `Skills`. In this scenario, a skill is a cooking technique, like baking, frying, etc. So each recipe has a certain set of associated skills. I want to search all the recipes like this: 1. Find all recipes that use any given set of skills (e.g. `Baking` OR `Frying` OR both) **EDIT...
Two queries to DB: ``` def self.find_recipes_that_require_any_of_these_skills(*known_skill_ids) Recipe.joins(:skills) .merge(Skill.where(id: known_skill_ids)) .where("recipes.id NOT IN (?)", Recipe.joins(:skills).merge(Skill.where("skills.id NOT IN (?)", known_skill_ids)).uniq.pluck(:id)).uniq end ``...
``` def self.find_recipes_that_require_any_of_these_skills(*known_skill_ids) self.includes(:skills).where(skills: { id: known_skill_ids }) end ```
Rails query with multiple conditions on the same field
[ "", "sql", "ruby-on-rails", "ruby", "postgresql", "activerecord", "" ]
this is a MS-SQL there are many rows of data duplicated , some of them get the latest update, some not. I want to update those old data with ones get latest info. ``` from: orderNum itemID orderTime desc 7247168 101 2013-08-11 09:51:39.20 desc_1...
If you are using SQL Server 2012, you can do this with `last_value`: ``` with toupdate as ( select t.*, last_value("desc") over (partition by itemID order by orderTime) as lastdesc from table t ) update toupdate set "desc" = lastdesc; ``` If you are not using SQL Server 2012, you an emula...
Something like this (won't work in SQL Server 2000 or earlier)? Don't try this on a production table; make a temporary copy table to try it. ``` ;WITH MaxT AS ( SELECT itemID ,maxOrderTime = MAX(orderTime) FROM myTable ), MaxTDesc AS ( SELECT itemID ,desc ...
SQL update other rows by one latest date row
[ "", "sql", "sql-server", "" ]
I am trying to create a simple trigger in an oracle 10g database. This script to Create the trigger runs clean. ``` CREATE OR REPLACE TRIGGER newAlert AFTER INSERT OR UPDATE ON Alerts BEGIN INSERT INTO Users (userID, firstName, lastName, password) VALUES ('how', 'im', 'testing', 'this trigger') END; ...
Oracle will try to recompile invalid objects as they are referred to. Here the trigger is invalid, and every time you try to insert a row it will try to recompile the trigger, and fail, which leads to the ORA-04098 error. You can `select * from user_errors where type = 'TRIGGER' and name = 'NEWALERT'` to see what erro...
**Cause**: A trigger was attempted to be retrieved for execution and was found to be invalid. This also means that compilation/authorization failed for the trigger. **Action**: Options are to resolve the compilation/authorization errors, disable the trigger, or drop the trigger. **Syntax** ``` ALTER TRIGGER trigger_...
Oracle Trigger ORA-04098: trigger is invalid and failed re-validation
[ "", "sql", "oracle", "oracle10g", "ora-04098", "" ]
I came across a question that states Consider the following relation schema pertaining to a students * database: Student (**rollno**, name, address) * Enroll (**rollno, courseno**, coursename) where the primary keys are shown underlined. The number of tuples in the Student and Enroll tables are 120 and 8 respectivel...
If there was a referential constraint in place ensuring that every rollno in Enroll must also appear in Student then your answer of 8 for both minimum and maximum would be correct. The question doesn't actually mention any such constraint however. There's no need to assume that the RI constraint exists just because the...
I hope, you understood what Natural Join exactly is. You can review [here](http://www.w3resource.com/sql/joins/natural-join.php). If the tables R and S contains common attributes and value of that attribute in each tuple in both tables are same, then the natural join will result n\*m tuples as it will return all combi...
maximum and minimum number of tuples in natural join
[ "", "sql", "join", "relational-database", "tuples", "natural-join", "" ]
I'm new to SQL. I have a table 'Customers' and it looks like this. ![enter image description here](https://i.stack.imgur.com/mFblN.png) I would like to select 'Gender' AS Gender Column and 'Age' as Age column which would be like this. ![enter image description here](https://i.stack.imgur.com/t1H7x.png) I've tried s...
One way to go about it is to use conditional aggregation ``` SELECT name, MAX(CASE WHEN field = 'Gender' THEN value END) gender, MAX(CASE WHEN field = 'Age' THEN value END) age FROM customers GROUP BY name ``` The other way (if you're interested only in these two columns) would be ``` SELECT c1.name...
I have not tested this, but give something like this a try: ``` Select c.Name, (Select c2.Value from customers c2 Where c2.Name = c.Name And c2.Field = 'Gender') as Gender, (Select c2.Value from customers c2 Where c2.Name = c.Name And c2.Field = 'Age') as Age From Customers c Group By c.Name ``` PS I apologiz...
How to select Column value as Column name with conditions in SQL table
[ "", "mysql", "sql", "" ]
I am using SQL Server 2012 sp1 .I have a table column with the following Date Time values. ``` BLDCHKDT ----------------------- 2013-06-19 00:00:00.000 2013-07-22 00:00:00.000 2013-08-21 00:00:00.000 2013-09-20 00:00:00.000 2013-11-18 00:00:00.000 ``` I would like to retrieve the date and Time in the following format...
You can do it this way: ``` declare @value datetime = getdate() select replace(convert(varchar(20), @value, 104), '.', '') date_part, left(replace(convert(varchar(20), @value, 114), ':', ''), 8) time_part ``` returns 23032014, 17174466 for 2014-03-23 17:17:44.660
Since you're using SQL Server 2012 you can use the `FORMAT()` function: ``` SELECT FORMAT(BLDCHKDT,'ddMMyyyy') , FORMAT(BLDCHKDT,'hhmmssfff') ```
Date and Time Format Conversion in SQL Server 2012
[ "", "sql", "sql-server", "date", "datetime", "sql-server-2012", "" ]
Write SQL code to find the **top 6** Client Country for each company. ![image](https://i.stack.imgur.com/wDXQc.jpg) How to approach this query? So far I am thinking:- ``` select top 6 Client_Country, count(*) Total from table group by Client_Country order by total desc ```
To get the top for each country, you'll need to use a windowing function. Otherwise, you'll just get the top 6 overall. I'm not sure what RDBMS you're using, but in SQL Server you can do something like this: ``` ;WITH top_cte AS ( SELECT *, ROW_NUMBER() OVER(PARTITION BY Company ORDER BY Revenue DESC) AS [Rank] F...
Try this ``` SELECT * FROM ( SELECT *,Row_Number() Over(Partition By Company Order By (Select Null)) RN FROM TAble1 ) AS T Where RN < 7 ```
SQL code to find the top 6
[ "", "sql", "" ]
I have a column which is of type integer array. How can I merge all of them into a single integer array? For example: If I execute query: ``` select column_name from table_name ``` I get result set as: ``` -[RECORD 1]---------- column_name | {1,2,3} -[RECORD 2]---------- column_name | {4,5} ``` How can I get `{1,2...
You could use [`unnest`](http://www.postgresql.org/docs/current/interactive/functions-array.html#ARRAY-FUNCTIONS-TABLE) to open up the arrays and then [`array_agg`](http://www.postgresql.org/docs/current/interactive/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) to put them back together: ``` select array_agg(c) ...
Define a trivial custom aggregate: ``` CREATE AGGREGATE array_cat_agg(anyarray) ( SFUNC=array_cat, STYPE=anyarray ); ``` and use it: ``` WITH v(a) AS ( VALUES (ARRAY[1,2,3]), (ARRAY[4,5,6,7])) SELECT array_cat_agg(a) FROM v; ``` If you want a particular order, put it within the aggregate call, i.e. `array_cat_a...
How to merge all integer arrays from all records into single array in postgres
[ "", "sql", "arrays", "postgresql", "" ]
the above question is very unclear let me show you what I mean.. I have a table of the following form ``` name ---- measure ----- value xxx-----------m1--------------x1 xxx-----------m2--------------x2 xxx-----------m3--------------x3 yyy-----------m1--------------y1 yyy-----------m2--------------y2 yyy-----------m3-...
You can do this to pivot your table ``` select name, MAX(case when measure = 'm1' then value end) m1, MAX(case when measure = 'm2' then value end) m2, MAX(case when measure = 'm3' then value end) m3 from tableName group by name ``` [**SQL FIDDLE DEMO**](http://www.sqlfiddle.com/#!12/5b5ff/1) To handle pivoting...
If the columns `m1`, `m2` and `m3` are fixed then this is the way: ``` UPDATE tbl SET m1 = t.value FROM tbl t WHERE tbl.name = t.name AND measure = 'm1'; ``` And similarly for `m2` and `m3`. Only that this will create duplicates. To remove which, you should do this: ``` DELETE FROM tbl WHERE measure = 'm2' OR meas...
sql query to convert existing column entries into row headers
[ "", "sql", "database", "postgresql", "pivot", "" ]
I have a query that was written for SQL Server 2012, and uses the `try_convert()` function. I now need to execute the query on SQL Server 2008 R2 Express, and it is my understanding that `try_convert()` isn't a supported function in 2008 R2. My current query contains this block: ``` CASE WHEN (try_convert(decimal, te...
`try_convert()` attempts to do the convert. This is a nice way of handling conversion errors (or at least better than SQL Server previously did, which was nothing). You can use `like` to see if the string "looks" like a valid decimal. Here is one attempt: ``` CASE WHEN tew_userdata_locTo.use_data0 not like '%[^0-9.]%'...
I wrote a useful scalar function to simulate the TRY\_CAST function of SQL SERVER 2012 in SQL Server 2008. ``` dbo.TRY_CAST(Expression, Data_Type, ReturnValueIfErrorCast) ``` > The two main differences with TRY\_CAST Function fo SQL Server 2012 are that you must pass 3 parameters and you > must additionally perform a...
try_convert in SQL Server 2008 R2 Express
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2008-r2", "" ]
I recently appeared for an interview and was asked to write SQL query for this question- There is table visit(person,theatre) which denotes that a person p visits a theatre t. Now a person p1 is considered to be more movie lover if he visits every theatre that another person p2 visits. I was supposed to write an SQL q...
The description is *quite vague*, so if we state the problem as "is there any person who has visited all the theaters all other persons have" we can put it like that: ``` select v.person from visit v where v.theatre = all ( select vt.theatre from visit vt) ```
Description is vague, but something like ``` select person, count(*) as cnt from visit group by person order by cnt desc ```
SQl query for (person,theatre) relation
[ "", "sql", "database", "" ]
Is there a better (*more efficient*) way to make this query? I don't want do search twice in the same query `(SELECT PDATA1 ...)` ``` SELECT package_ID FROM t_package WHERE parent_ID IN (SELECT PDATA1 FROM t_object WHERE stereotype = 'Process' AND object_type = 'Package') OR pa...
I believe this can be accomplished entirely without subqueries. ``` SELECT DISTINCT(tp.package_ID) FROM t_package tp INNER JOIN t_object tobj ON tobj.PDATA1 = tp.parent_ID OR tobj.PDATA1 = tp.package_ID WHERE tobj.stereotype = 'Process' AND tobj.object_type = 'Package' ```
Use EXISTS, like this - ``` SELECT package_ID FROM t_package t WHERE exists(SELECT * FROM t_object o WHERE stereotype = 'Process' AND object_type = 'Package' and (o.PDATA1=t.parent_ID OR o.PDATA1=t.package_ID) ) ```
Improving query having two where ... in clauses
[ "", "sql", "" ]
Consider the tables (of a Bank): Accounts ![enter image description here](https://i.stack.imgur.com/pyJck.gif) Clients ![enter image description here](https://i.stack.imgur.com/GHdwS.gif) I want to return all the clients ID , of the clients that have more than one account in the bank My suggestion : ``` SELECT c...
``` SELECT c.Client_id_number , c.firstName_client , c.lastName_Client , COUNT(a.Account_number) as number_of_accounts FROM Clients AS c LEFT JOIN Accounts AS a ON a.Client_id_number = c.Client_id_number GROUP BY Client_id_number HAVING COUNT(a.Account_number) >= 2; ``` **[See this for correct SQL clasues order](https...
``` SELECT Account_number, Client_id_Number FROM Accounts GROUP BY Account_number, Client_id_Number having count(*) > 1 ```
WHERE clause causes syntax error in Mysql query
[ "", "mysql", "sql", "" ]
My friend asking me if there a way to use 1 query to select datetime and use it for any database. Atm he using this query for Oracle : ``` SELECT vt_sysdate() FROM dual; ``` I know dual table is for Oracle only. But he want to use this same query for other database, for example PostgreSQL, as well. So is there a wa...
Thank everyone for your support. After looking at everyone answer, after a while discuss with my friend, we came to a conclusion that it won't be possible to use one query for all database. So we create a function, check database, use correct function to get time and return it. We will have to create a dummy table du...
No, I don't think so, because Oracle insists on being weird, and MS SQL doesn't seem to support the standard `current_date` at all. [MySQL accepts `SELECT current_date;`, doesn't understand `VALUES`](http://sqlfiddle.com/#!2/636321/2). [PostgreSQL accepts `SELECT current_date;` or `VALUES`](http://sqlfiddle.com/#!15/...
Query to get datetime for every database
[ "", "sql", "oracle", "postgresql", "datetime", "" ]
I have a column in database: ``` Serial Number ------------- S1 S10 ... S2 S11 .. S13 ``` I want to sort and return the result as follows for serial number <= 10 : ``` S1 S2 S10 ``` One way I tried was: ``` select Serial_number form table where Serial_Number IN ('S1', 'S2',... 'S10'); ``` This solves the purpose ...
For Postgres you can use something like this: ``` select serial_number from the_table order by regexp_replace(serial_number, '[^0-9]', '', 'g')::integer; ``` The `regexp_replace` will remove all non-numeric characters and the result is treated as a number which is suited for a "proper" sorting. **Edit 1:** You can ...
Here is an easy way for this format: ``` order by length(Serial_Number), Serial_Number ``` This works because the prefix (`'S'`) is the same length on all the values.
Sort alphanumeric column
[ "", "sql", "postgresql", "alphanumeric", "natural-sort", "" ]
mysql query ``` CREATE TABLE IF NOT EXISTS 'sadakin'.'gcm_users' ( 'id' int( 11 ) NOT NULL AUTO_INCREMENT , 'gcm_regid' text, 'name' varchar( 50 ) NOT NULL , 'email' varchar( 255 ) NOT NULL , 'imei' varchar( 20 ) NOT NULL , 'created_at' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP , ...
Use backticks to enclose identifiers. Quotes are just for strings: ``` CREATE TABLE IF NOT EXISTS `sadakin`.`gcm_users` ( `id` int( 11 ) NOT NULL AUTO_INCREMENT , `gcm_regid` text, `name` varchar( 50 ) NOT NULL , `email` varchar( 255 ) NOT NULL , `imei` varchar( 20 ) NOT N...
There is no need of any single quotes on column names ``` CREATE TABLE IF NOT EXISTS sadakin.gcm_users ( id int( 11 ) NOT NULL AUTO_INCREMENT , gcm_regid text, name varchar( 50 ) NOT NULL , email varchar( 255 ) NOT NULL , imei varchar( 20 ) NOT NULL , created_at t...
mysql syntax error why?
[ "", "mysql", "sql", "" ]
I need to find records by one column but if there was no records i need to search in by another column but the first column has precedence. Consider scenario: ``` find records matching column_1 if no records matching column_1, find records matching column_2 if records matching column_1 found, find the subset which ...
Such queries (try to find records with certain criteria and if that fails try with other) are complicated. Here is your criteria: * If there exist records with matching column\_1 and matching column\_2, then show only these. * If there exist records with matching column\_1 and none of these matching column\_2, then s...
You don't care about the order of the parts of the `where` clause - they can be interchanged at will, and it's a good thing. The usuall way to do what you're asking would be using the `or` operator: ``` where column_1 = @param or column_2 = @param ``` The query will not let you return the same row twice or more, it ...
How would be possible to specify the order how the WHERE clause is evaluated?
[ "", "sql", "sql-server-2008", "" ]
I have a table CUSTOMERS (ID,NAME,REGISTRATION\_DT). It has following values - 1,Alex,093013 2,Peter,012512 3,Mary,041911 . . . I want to be able to select REGISTRATION\_DT column and have the values retun as DATETIME. Is there any query to convert the existing varchar datatype in REGISTRATION\_DT column to da...
The below example requires the year to always be in 2000. you will also need to change the string YourTable to the table you want to query from. ``` SELECT Id ,Name --Convert To Date Time ,CONVERT(datetime, -- Add 20 to the final 2 numbers to represent the year i.e 2013 ...
The only way is to convert the varchar to date. Try something like ``` SELECT CONVERT(DATE, LEFT(REGISTRATION_DT, 2) + '/' + LEFT(RIGHT(REGISTRATION_DT, 4), 2) + '/20' + RIGHT(REGISTRATION_DT, 2)) ``` An example [**SQL FIDDLE**](http://sqlfiddle.com/#!3/d41d8/32150) her...
Is it possible to convert string column to datetime in sql server?
[ "", "sql", "sql-server", "datetime", "" ]
I can **able to insert** the records into the temp table. From the same temp table **i need to delete the records** according to another condition **Here is my code :** ``` DECLARE @tempDataTable Table ( Id bigint, Title varchar(max), Forename varchar(max), Surname varchar(max), Addr1 varchar(max)...
Your problem is that you need to use the name of the variable in your dynamic SQL, like ``` SET @sqlQuery = 'DELETE FROM @tempDataTable' ``` But you won't be able to use your table variable inside dynamic SQL this way - it won't be visible inside the scope of that dynamic SQL execution. You would have to declare ever...
> While inserting it throws an error of - Must declare the scalar variable "@tempDataTable". Did you ever look at the SQL you are sending to the server? Not the source. Basically print out the SQL. SET @sqlQuery = 'DELETE FROM '+ @tempDataTable +' translated into ``` DELETE FROM (content of @tempDataTable) ``` if ...
How to delete the records in local table using sql server
[ "", "sql", "sql-server", "" ]
When I execute the following query :- ``` SELECT users.id, users.username, users.last_login, profile_pictures.pic_resized, profile_pictures.pic_blurred, user_profile.date_of_birth, user_profile.u_country, matches.total_score AS score, favorites.id AS is_favorite, relationships.id AS is_match, profile_visitors.id AS ...
you can use this :- ``` SELECT users.id, users.username, users.last_login, profile_pictures.pic_resized, profile_pictures.pic_blurred, user_profile.date_of_birth, user_profile.u_country, matches.total_score AS score, if(isnull(favorites.id),-1,favorites.id) AS is_favorite, if(isnull(relationships.id),-1,relationship...
If you want to return something other than NULL, if that's what is in the field use a CASE statement to overide what is returned. ``` case when favorites.id is NULL then '-1' else favorites.id end as is_favorite ```
Mysql set default value if entry does not exist
[ "", "mysql", "sql", "" ]
How do I determine if NULL is contained in an array in Postgres? Currently using Postgres 9.3.3. If I test with the following select it returns `contains_null = false`. ``` select ARRAY[NULL,1,2,3,4,NULL]::int[] @> ARRAY[NULL]::int[] AS contains_null select ARRAY[NULL,1,2,3,4,NULL]::int[] @> NULL AS contains_null ```...
``` select exists ( select 1 from unnest(array[1, null]) s(a) where a is null ); exists -------- t ``` Or shorter: ``` select bool_or(a is null) from unnest(array[1, null]) s(a) ; bool_or --------- t ```
One more construction, like @Clodoaldo Neto proposed. Just more compact expression: ``` CREATE TEMPORARY TABLE null_arrays ( id serial primary key , array_data int[] ); INSERT INTO null_arrays (array_data) VALUES (ARRAY[1,2, NULL, 4, 5]) , (ARRAY[1,2, 3, 4, 5]) , (ARRAY[NULL,2, 3, NULL, 5]) ; ...
How to determine if NULL is contained in an array in Postgres?
[ "", "sql", "arrays", "postgresql", "" ]
I have problem in getting the desired output with the SQL query. My sql data is as follows: ``` TOTAL Charge PAYMNET A B C D E MonthYear ------- ----------- ----------- --------- -------- ---------- ------- ------- ---------- 661 157832.24 82967.80 700.00 10....
I have tried this code. Please check and let me know if it works I know that it doesnt look so good. Also not sure how it will be performance wise. ``` --Can have more columns like A,B,... DECLARE @tbl TABLE ( TOTAL INT, CHARGE FLOAT, PAYMENT FLOAT, MONTHYEAR VARCHAR(50) ) --Test data INSERT INTO @tbl SELECT 661, 1...
I would imagine the reason you are only getting 3 or 4 months is because you don't have data for the missing months? If you want to display columns for missing months you will need to either: 1. Create a Table datatype with all the months you want to display and left join the remainder of the tables to it in your q...
transpose rows to columns in sql
[ "", "sql", "sql-server", "sql-server-2008", "unpivot", "" ]
I'm using SQL Server 2012. I need to implement a search functionality using a **single** text field. Let's say I have the following table: ``` -------------------------------------------------------------------------------- FIRSTNAME LASTNAME CITY PROMOYEAR EMPLOYOR ---------------------------------...
Here is a solution. I have limited the search to 6 words. For each word, I check if it exists in the concatenated columns. I get a "score" for each record by adding +1 each time a word is found in it. I return the records that have the best score. The function : ``` CREATE FUNCTION [dbo].[SEARCH_SINGLE] ( @langI...
How about adding another field e.g. a text field containing all the information from the other fields. ``` FIRSTNAME LASTNAME CITY PROMOYEAR EMPLOYOR SEARCHFIELD John Doe Boston 2005 Mc Donald John Doe Boston 2005 Mc Donald ``` And make the search on this field. It's not el...
SQL simple search functionality across multiple tables
[ "", "sql", "sql-server", "search", "" ]
I am trying to group the number of hours that employees worked for the last 4 weeks but I want to group them on a weekly basis. For example: ``` WEEK HOURS Feb 24 to March 2 55 March 3 to March 9 40 March 10 to March 16 48 March 17 to March 23 37 ``` This is what I have so ...
Try something like ``` SELECT DATEADD(DD, CONVERT(INT, (DATEDIFF(DD, '1/1/1900', t.DT)/7)) * 7, '1/1/1900') [WeekBeginDate], DATEADD(DD, (CONVERT(INT, (DATEDIFF(DD, '1/1/1900', t.DT)/7)) * 7) + 6, '1/1/1900') [WeekEndDate], SUM(HOURS) AS NUM_HRS FROM MyTable ...
``` SET DATEFIRST 1 SELECT DATEPART(WEEK,DT) AS WEEK, SUM(HOURS) AS NUM_HRS FROM MyTable WHERE DT >= DATEADD(WEEK, -4, GetDate()), GROUP BY DATEPART(WEEK,[DT]) ```
How to group daily data on weekly basis using sql
[ "", "sql", "sql-server", "t-sql", "" ]
I have SQL Server table that contains columns of type `varchar(50)` as a result of a CSV import using the SQL Server Import wizard. I was wanting to know how I can change this data type to `nvarchar(9)` without getting a SQL Server truncation error. I tried doing a bulk update to set the data types and column sizes t...
Since you are willing to lose data and nvarchar will only be able to store 9 non-unicode charaters, then select only 9 characters from your source table, You do the truncation rather than Sql server doing it for you. The Following Query will trim any White spaces from the strings, Then take only 9 characters from the ...
Bulk insert into temp table with varchar(50) and insert to actual table ``` insert into tableName select cast(tempcolumn as nvarchar(9)) from temptable ```
Converting varchar to nvarchar in SQL Server failed
[ "", "sql", "sql-server", "types", "type-conversion", "" ]
I have three tables; doctor, person, and appointment. doctor table: ``` +-----------+----------+---------+----------------+----------------+ | doctor_id | phone_no | room_no | date_qualified | date_appointed | +-----------+----------+---------+----------------+----------------+ | 50 | 1234 | 1 | 1963-...
You need an additional join to the `person` table. Apparently, the `doctor_id` is the link. Yuck. This should be an explicit column rather than a re-use of the id. ``` select d.doctor_id, p.initials, p.last_name, count(appointment.appt_time) as no_appt from doctor d left join appointment a on d.doctor_id = a...
``` select doctor.doctor_id, person.initials, person.last_name, count(appointment.appt_time) as no_appt from doctor left join appointment on doctor.doctor_id = appointment.doctor_id left join person on person.person_id = appointment.patient_id group by doctor.doctor_id; ```
SQL Database - query to produce a list of doctor IDs and their names with the number of appointments they have?
[ "", "mysql", "sql", "database", "" ]
I have a query which returns distinct records on 2 columns, however I need to sort the results on those 2 columnns and 1 additional column. When I try the SQL below I get the error shown. SQL: ``` SELECT DISTINCT vers, revs FROM tblMVer WHERE mid = 194 ORDER BY date_deployed DESC, vers DESC, revs DESC ``` Error: `...
You cann't order by Date simply because they are different I guess. But if you will take last date, you can do like this: ``` SELECT vers, revs FROM ( SELECT MAX(date_deployed) AS d, vers, revs FROM tblMVer WHERE mid = 194 GROUP BY vers, revs ORDER BY d DESC, vers DESC, revs DESC ) AS temp ```
There is no **date\_deployed** in select Try this ``` SELECT DISTINCT vers, revs FROM tblMVer WHERE mid = 194 ORDER BY vers,revs DESC ``` but Still you want to order by date\_deployed Try this ``` SELECT vers, revs FROM ( SELECT DISTINCT vers, revs,date_deployed FROM tblMVer WHERE mid = 194 OR...
MSSQL Select Distinct and Sorting
[ "", "sql", "sql-server", "" ]
I've got a web-application that requires data from a db. It is a simple list of jobs where each job has certain tags and also a location. Now I want to get a list that gives me all possible filter options... like this: ``` FILTER-ATTRIBUTE FILTER-CATEGORY MATCHING-JOBS programming tag 9 ca...
After some more research, I came across an interesting approach and I would like to share this with with you: ``` SELECT name, COUNT(job_id) FROM ( SELECT j.id AS job_id, loc.city, j.company, jt.tag_name FROM job_tag_new jt LEFT JOIN job j ON jt.job_id = j.id LEFT JOIN location loc ON loc.id ...
there are two other approaches that you may want to explore: windowing: ``` select distinct tag, location, company, count(id) over(partition by tag) thistag, count(id) over(partition by location) thisloc, count(id) over(partition by company) thiscompany from job order by tag, location ``` aggregation with cube: ``...
SQL query to get filters with expected values for a web view
[ "", "sql", "sql-server", "t-sql", "union", "" ]
In Ruby: ``` -2 % 24 => 22 ``` In Postgres: ``` SELECT -2 % 24; ?column? ---------- -2 SELECT mod(-2,24); mod ----- -2 ``` I can easily write one myself, but I'm curious whether Postgres has a real modulus operation, as opposed to remainder after division.
``` SELECT MOD(24 + MOD(-2, 24), 24); ``` will return 22 instead of -2
It seems that I won't find anything easier than: ``` CREATE OR REPLACE FUNCTION modulus(dividend numeric, divisor numeric) RETURNS numeric AS $$ DECLARE result numeric; BEGIN divisor := ABS(divisor); result := MOD(dividend, divisor); IF result < 0 THEN result := result + divisor; END IF; RETURN result...
Real, mathematical "modulo" operation in Postgres?
[ "", "sql", "postgresql", "" ]
I just try **simple** joins with C# using oracle db. Should be no big deal. But it **ALWAYS** fails. It works in MS-Access. Where is the problem ? *(OleDb or Odbc makes no difference here, I tried both)* **Edit:** * Might Oracle version be the problem ? (seems we are using 8.1.7.0.0 and 8.1.5.0.0 modules) **Code:** ...
ANSI joins (ex. `inner join`) were first supported in 9i. You will need to use the old syntax: ``` select a.KEY, b.GREG from INFOR.ZEITEN a, INFOR.ZEITEN b where (a.AUSWEIS = b.AUSWEIS) and (a.KEY like '1') ``` Note that the `like` operator is equivalent to `=` in this case, but you probably know tha...
The word `key` is a reserved word. That means that it is a very poor choice for an identity. You need to escape it with a double quote. This might work: ``` query = "select a.\"KEY\", b.GREG from INFOR.ZEITEN a inner join INFOR.ZEITEN b on (a.AUSWEIS...
Why do SQL joins fail in Oracle?
[ "", "sql", "database", "oracle", "join", "" ]
I have this SQL Query: ``` SELECT COUNT(DISTINCT callid) as r FROM voipwallboard_ast_queue_log WHERE queuename = :queuename AND time > :date AND callid NOT IN ( SELECT callid FROM voipwallboard_ast_queue_log WHERE event IN ('CONNECT', 'ABANDON', ...
**Sub query:** ``` SELECT callid FROM voipwallboard_ast_queue_log WHERE event IN ('CONNECT', 'ABANDON', 'AGENTCALLBACKLOGOFF', 'AGENTCALLBACKLOGIN') ``` Selects the list of callids from voipwallboard\_ast\_queue\_log table where event is any of `'CONNECT', 'ABANDON', 'AGENTCALLBACKLOGOFF', 'AGENTCALLBACKLOGIN'` **M...
it returns all the **unique** `callid` filtered by a specified `queuename` and `date` for ALL the events exept `CONNECT`, `ABANDON`, `AGENTCALLBACKLOGOFF` AND `AGENTCALLBACKLOGIN`
explain SQL Query with NOT IN etc
[ "", "sql", "" ]
I have two separate queries that count number of exceptions in my database. I need to return both results in the same query, how do I bring it all together correctly? ``` SELECT ( IF EXISTS (SELECT * FROM exception AS ex INNER JOIN exceptionDefinition AS ed ON ex.exceptionDe...
Use [CASE](http://msdn.microsoft.com/en-us/library/ms181765.aspx). ``` SELECT ( CASE WHEN EXISTS (SELECT * FROM exception AS ex INNER JOIN exceptionDefinition AS ed ON ex.exceptionDefId = ed.exceptionDefId WHERE ex.customerId='{5B65755C-3B66-434E-AC03-942...
Why don't you declare computedExceptionCount and manualExceptionCount above, then select both in a simple select statement: ``` Declare @computedExceptionCount INT, @manualExceptionCount INT Select @computedExceptionCount as computedExceptionCount,@manualExceptionCount as manualExceptionCount ``` or you can try ...
Returning 2 count results in statement
[ "", "sql", "t-sql", "" ]
Currently I am getting output for score as " 25 / 50 " as string through SQL, now I need to calculate percentage from this score and return that value using a SQL statement in Post Gres SQL. ``` SELECT es.score FROM emp_scores es WHERE id = 123; ``` This returns me a string as " 25 / 50 ". Now I want to calculate the...
you need to split your data first then you can calculate percentage... you can use ``` split_part(string text, delimiter text, field int) //Split string on delimiter and return the given field (counting from one) ``` here is example ``` SELECT (CAST(coalesce(split_part(es.score,'/',2)*100), '0') AS integer)...
``` select cast(substring(es.score,0,patindex('%/%',es.score)) as int)/ cast(substring(es.score ,patindex('%/%',es.score)+1 ,len(es.score)-patindex('%/%',es.score)) as int)*100 FROM emp_scores es WHERE id = 123; ```
I need to calculate percentage from score using a SQL statement
[ "", "sql", "postgresql", "percentage", "" ]
I need create SQL query, which retrieve articles, which have given tags. Relation is M:N, so one article can has associated N tags. ``` id_article id_tag article_has_tag 1 1, SQL 1, 1 2 2, HTML 1, 4 3 3, PHP 2, 1 ...
``` SELECT * FROM article_has_tag a where a.id_tag = 1 OR a.id_tag = 4 group by id_article having count(*)=2 ```
``` SELECT * FROM article_has_tag a where a.id_tag = 1 and a.id_tag = 4 ``` Returns 0 rows meaning u are using AND ``` where a.id_tag = 1 and a.id_tag = 4 ``` So its looking id\_tag is 1 and its 4 so it never happens. In other words you are asking to find something on a column which co-exist at the same time. So y...
Fetching from an associative table
[ "", "mysql", "sql", "" ]
I have this query which I have been messing with and cannot seem to see what to change in order to receive the results I want. I want to sum sales by `Emp_ID` by day, but only sum the ones over $10000 for that day. Below is what I currently have ``` SELECT Emp_ID, sum(SaleA+SaleB) as TotalSales, sum(SaleA...
Don't have SQL Server 2000 to test with, but you *should* be able to get it done using a plain subquery, something like; ``` SELECT SUM(TotalSales) TotalSales, SUM(TSalesAftComm) TSalesAftComm, SUM(NumOfSales) NumOfSales, SaleDate FROM ( SELECT Emp_ID, sum(SaleA+SaleB) as TotalSales, sum(Sal...
Without looking at actual data/schema, and looking at your expected results, what happens if you try this (look at the group by section, showing group by TotalSales; employee id removed too)? ``` SELECT sum(SaleA+SaleB) as TotalSales, sum(SaleA+SaleB-CommA-CommB) as TSalesAftComm, count(Emp_ID) as NumOfSal...
GROUP BY not returning correct totals
[ "", "sql", "t-sql", "sql-server-2000", "" ]
I am running PostgreSQL 9.3.1. I have `test` database and `backup` user which is used to backup the database. I have no problems with granting privileges to all current tables, but I have to grant privileges each time the new table is added to schema. ``` createdb test psql test test=# create table foo(); CREATE TABL...
It looks like the solution is to alter default privileges for `backup` user: ``` alter default privileges in schema public grant all on tables to backup; alter default privileges in schema public grant all on sequences to backup; ``` From the comment by Matt Schaffer: > As caveat, the default only applies to the use...
If you want the **backup** user to have access to the **future** tables of user**N**, you must run the code below under each user**N** who creates new tables, because ALTER DEFAULT PRIVILEGES... works only for objects **by that user under whom you run** ALTER DEFAULT PRIVILEGES... ``` ALTER DEFAULT PRIVILEGES IN SCHEM...
Grant privileges on future tables in PostgreSQL?
[ "", "sql", "database", "postgresql", "" ]
Imagine the following scenario: ``` ColA | ColB 1 | 1 1 | 2 1 | 3 2 | 1 2 | 2 2 | 3 3 | 1 3 | 2 3 | 3 ``` Using SQL Server 2008, how would I count an occurrence such that the combination (1,2) would be the same as (2,1) and therefore my results would be as follows: ``` ColA | ColB | Count ...
Try this: ``` ;with cte as (select ColA, ColB, case when ColA < ColB then ColA else ColB end as ColC, case when ColA > ColB then ColA else ColB end as ColD from yourtable) select ColC as ColA, ColD as ColB, count(1) as Count from cte group by ColC, ColD order by ColC, ColD ```
Before grouping, normalize the data by making `Col1 = MIN(Col1, Col2)` and `Col2 = MAX(Col1, Col2)`. This converts each possible combination to a canonical one. Then, do the usual grouping.
Count Unique Combination of Values
[ "", "sql", "sql-server", "" ]
I have two tables: **tata\_data1:** ``` Password | Region | Company | System ------------------------------------- a02040 | Del | xx | abc a01917 | Mum | xxx | pqr a01916 | Mum | x | zzz a01906 | Nag | x | pny ``` and **tata\_passwords:** ``` Password | Region | Company ----...
Try this: ``` SELECT * FROM tata_passwords WHERE (Password, Region, Company) NOT IN ( SELECT Password, Region, Company FROM tata_data1 ) ``` **EDIT:** Now when Password is primary key, one could reduce the query to: ``` SELECT * FROM tata_passwords WHERE Password NOT IN ( SELECT Password FROM tata_data1 ) ```
Using a LEFT OUTER JOIN:- ``` SELECT tata_passwords.* FROM tata_passwords LEFT OUTER JOIN tata_data1 ON tata_passwords.Password = tata_data1.Password WHERE tata_data1.Password IS NULL ```
How to retrieve rows NOT common in two tables
[ "", "mysql", "sql", "" ]
Okay i have 2 tables, **url\_table** ``` id link_url ``` **tag table** ``` id link_tags ``` i'd like to join them, to create a view or table like, ``` id ,link_tag1, link_tag2, link_tag3..... ``` sample data: url\_table ``` [1 | w3schools.com] [2 | php.net] ``` sample\_data: tag\_table: ``` [1 | html] [1 |...
You can use MySQL's `GROUP_CONCAT()` function for this: ``` SELECT u.url ,GROUP_CONCAT(t.tag) FROM url_table u JOIN tag_table t ON u.id = t.id GROUP BY u.url ``` Note: In the example the `JOIN` doesn't really add anything as `ID` and `tag` could just be had from the `tag_table`, but I included it assuming ther...
``` Select id, group_concat(`Link_Tag` separator ',') as mTags FROM tag_table Group by ID ``` As your results don't really render the URL, there's no need for a join. Everything can be done direct on the tag\_table.
optimum way to join the following two tables?
[ "", "mysql", "sql", "database", "database-design", "" ]
I'm trying to do some set operations in PostgreSQL 9.3. I have two tables, for simplicity let's call them `table_a` and `table_b`: ``` create table table_a(id varchar primary key); create table table_b(id varchar primary key); ``` And I have a simple query (in its simplest formulation, though it's a source for an in...
First thoughts: * Plain `EXCEPT` means `EXCEPT DISTINCT` which means it eliminates duplicate rows from its result. Use `EXCEPT ALL` if you can, it *should* be faster. * Don't use [combining queries](http://www.postgresql.org/docs/9.3/static/queries-union.html) if you have another options too, they are known to be slow...
How do these variants do? ``` select id from table_a a where not exists (select 1 from table_b b where b.id = a.id); ``` or: ``` select id from table_a left outer join table_b b on a.id = b.id where b.id is null; ``` If these perform better, it is simply that not as much effort has going into optimizing `...
Improve PostgreSQL set difference efficiency
[ "", "sql", "database", "performance", "postgresql", "" ]
I have a string variable that denotes a time: ``` @time = '5:00 PM' ``` I need to check if the current time `getdate()` is after or before `@time`. How can I do this in SQL?
This should do it: SQL 2008+ ``` if datediff(ss,cast(@time as time),cast(GetDate() as time)) < 0 print 'Future' else print 'Past' ``` Earlier: ``` if DatePart(hh,GETDATE())*60+DATEPART(mm,getDate()) < DatePart(hh,@time)*60+DATEPART(mm,@time) print 'Future' else Print 'Past' ```
One way, but not great on performance. ``` declare @time varchar(20) set @time = '5:00pm' select DatePart(hh,GETDATE())*60+DATEPART(mm,getDate()) as CurTime, DatePart(hh,@time)*60+DATEPART(mm,@time) as TheTime ```
Compare two time strings in SQL
[ "", "sql", "sql-server", "datetime", "sql-server-2005", "" ]
I'm in the process of trying to get the count from an output of a T-SQL query. Here's the sample table information... ``` ------------------------------------------------------ | order_no | company | destination | date | |-------------|-------------|--------------|----------| | 100 | Burger King ...
Does this help you ? ``` SELECT company, COUNT(destination) as company_destination, destination, count(destination) over() as TotalCities from dbo.burger_orders WHERE (date >= 20140301 AND date <= 20140331) group by company, destination ```
You are looking for [analytic functions](http://technet.microsoft.com/en-us/library/ms189461.aspx) Something [like this](http://sqlfiddle.com/#!6/4eee9/25): ``` SELECT company, company_orders, COUNT(destination) OVER () AS dest_count FROM ( SELECT company, COUNT(destination) as company_orders, destination F...
How to get a grand total of distinct cells based on T-sql count output?
[ "", "sql", "sql-server", "t-sql", "" ]
I have a query which gives me the last month's completed data ``` select * from Tabl where datepart(month, completed_date) = DATEPART(month, getDate())-1 and datepart(year, completed_date) = datepart(year, getDate()) ``` But it gives me wrong data when the current date is in january How can I write the condition t...
SQL Server's DATEADD function will help you here. ``` select * from Tabl where datepart(month, completed_date) = DATEPART(month, DATEADD(MM,-1,getDate())) and datepart(year, completed_date) = datepart(year, DATEADD(MM,-1,getDate())) ``` The 'MM' used is just a keyword for Month.
Well, try subtracting one month from the date instead: ``` select * from Tabl where month(completed_date) = month(dateadd(month, -1, getdate()) and year(completed_date) = year(dateadd(month, -1, getdate()); ``` But, if you have an index on `completed_date`, it is better to put all the operations on `getdate()` ...
How to get this condition in where clause of Sql
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
Could any one help me for the below request. I have data of One row for the Login DateTime and another row for the Logout Datetime. The rest of the fields are same. I need to combine both rows in to one with Login (Datetime) and Logout (Datetime). Sample Data ``` ID Code DateTime User Status 35 100 1/1/2...
This finds the next date/time with an 'OUT' after each 'IN' : (simplified to match small data sample, extra code required) ``` With YourData as ( SELECT 35 as ID, 100 as Code, '1/1/2014 14:50' as yDatetime, 'a' as yUser, 'IN' AS status UNION ALL SELECT 35,100, '1/1/2014 15:45', 'a', 'OUT' UNION ALL SELECT 35,10...
Use the `ROW_NUMBER()` windowing function to determine the closest 'OUT' status for each 'IN' iteration: ``` SELECT * FROM ( SELECT t1.ID, t1.Code, t1.[Datetime] as Datetime1, tNext.[Datetime] as Datetime2, t1.[User], ROW_NUMBER() OVER (PARTITION BY t1.ID, t1.Code, t1.[User], t1.[Datetime] ORDER BY tNext.[D...
Combine Two Rows into One with Similar fields (DateTime) and NULL Vales in SQL
[ "", "sql", "sql-server-2008", "" ]
Each row in my table belongs to some *category*, has some *value* and other data. I would like to select each *category* with the most common *value* for it (doesn't matter which one if there are multiple), ordered by *category*. ``` some_table: expected result: +--------+-----+--- +--------+-----+ |c...
I would be inclined to do this using a correlated subquery: ``` select distinct category, (select value from some_table t2 where t2.category = t.category group by value order by count(*) desc limit 1 ) as mode_value from some_table t; ``` The name for the most com...
Here is one option, but I think it's slow... ``` SELECT DISTINCT `category` AS `the_category`, `value` FROM `some_table` WHERE `value`=( SELECT `value` FROM `some_table` WHERE `category`=`the_category` GROUP BY `value` ORDER BY COUNT(`value`) DESC LIMIT 1) ORDER BY `category`; ``` You can replace ...
Select the most common item for each category
[ "", "sql", "sqlite", "" ]
I am using the following query to get the latest 2 messages of the same conversation: ``` SELECT * FROM messages WHERE conversation_id IN ( 122806, 122807 ) GROUP BY conversation_id ORDER BY sent_on DESC LIMIT 2 ``` ![enter image description here](https://i.stack.imgur.com/XuGBG.png) Which return `message7` and `mes...
The canonical way to do this is with a counter in the `where` clause: ``` select m.* from message m where 2 >= (select count(*) from message m2 where m2.conversation_id = m.conversation_id and m2.sent_on >= m.sent_on ); ``` An index on `message(conversation_id, sen...
One way to go about this using `GROUP_CONCAT()` and the `SUBSTRING_INDEX()` but it will show you the messages seperated by seperator you specified in the query with conversation id not as individual row foreach message,you can use `ORDER BY` clause in group\_concat function also i have `ORDER BY sent_on DESC` so the me...
Use limit before group by
[ "", "mysql", "sql", "" ]
In my Oracle 11 database, I have a sql script for inserting(migrating) data from one table into another, this is a problem I encounter a lot, **for instance**: ``` INSERT INTO TargetTable (eventname, eventplace, eventdate) SELECT name, eventplace, "How to insert time here?" FROM SourceTable; ``` The SourceTable do...
For date fields just use sysdate, for varchar fileds I think you have done right, just add "default value" after select works.
Try this: ``` INSERT INTO TargetTable ( eventname, eventplace, eventdate) SELECT name, eventplace, SysDate -- <- Current Date and Time FROM SourceTable; ```
Oracle Sql: How to set a default column value on insert select
[ "", "sql", "oracle", "data-migration", "" ]
I'm relatively new to SQL. I'm trying to print a simple pattern through this code ``` declare n number(2):=5; temp number(2):=n; begin for a in 1..5 a:=a+1;loop for b in 1..temp loop b:=b+1; dbms_output.put_line(' '); temp:=temp-1; end loop; for c in 1...
Modifying the previous answers to actually give you Pascal's triangle, which you mentioned you were attempting in a comment: ``` set serveroutput on format wrapped declare n number(2):=5; begin for a in 1..n loop for b in 1..n-a loop dbms_output.put(' '); end loop; for c in 1..2*a-1 loop d...
When I took your code in my editor I first noticed, you tried to increase a before starting the loop, and Oracle gives first error at that point. And also it does not allow you to increase counter variable in for loop, (I don't know why) I checked on the internet and found that you can not set increment step for Oracle...
ERROR: Reference the counter as the target of an assignment - PL/SQL
[ "", "sql", "oracle", "" ]
I'm wondering if there is a simpler way to accomplish my goal than what I've come up with. I am returning a specific attribute that applies to an object. The objects go through multiple iterations and the attributes might change slightly from iteration to iteration. The iteration will only be added to the table if the...
The following query will return the matching value, if found, otherwise use a correlated subquery to return the value with the highest GenId and matching AttribId: ``` SELECT obj.Object_Id, CASE WHEN attr1.AttribDesc IS NOT NULL THEN attr1.AttribDesc ELSE attr2.AttribDesc END AS AttribDesc FROM Object_Table AS ...
Try this... Incase the logic doesn't find a match for the **Object\_table GENID** it maps it to the **next highest GENID** in the `ON` clause of the `JOIN`. ``` SELECT AttribDesc FROM object_TABLE A INNER JOIN Attribute_Table B ON A.AttrbId = B.AttrbId AND ( CASE ...
Is there a simpler way to write this query? [MS SQL Server]
[ "", "sql", "sql-server", "simplify", "" ]
I am trying to use the below query that shows **country** and **population** of *second most and second least populous* country. I figured out a way to select the population for those countries but I can't find any good way to implement selection of country names. ``` Select Max(population) From country Where popula...
``` select * from ( select country, population from ( select country, population from country order by population offset 1 limit 1 ) s union select country, population from ( select country, population ...
By using window function, you can do it simply like this: ``` with t as ( select population, row_number() over (order by population desc) mx, row_number() over (order by population asc) mn from country) select 'second most population', population from t where mx = 2 union all select 'second least...
Selecting two columns in same table multiple times
[ "", "sql", "postgresql", "union", "union-all", "sql-limit", "" ]
At work we did a project that required a team to count students 8 times a day over 5 days at specific time periods. They are, as follows :- ``` 09:00, 10:00, 11:00, 13:15, 14:15, 14:50, 15:50, 16:20. ``` Now, the data collected was put directly into a database via a web app. The problem is that database recorded each...
You may want some sort of Period table to store your segments. Then you can use that to join to your counts table. ``` CREATE TABLE [Periods] ( -- maybe [id] INT, [start_time] TIME, [end_time] TIME ); INSERT INTO [Periods] VALUES ('09:00','10:00'), ('10:00','11:00'), ('11:00','13:15'), ...
You can use the `DATEADD`and `DATEPART`functions to accomplish this together with a `CASE`expression. If you want more precise cutoffs between the `.14`and `.50`periods you can easily adjust the case statement and also if you want to minutes to be `.10`or`.15` ``` -- some test data declare @t table (the_time time) ins...
SQL - How to ignore seconds and round down minutes in DateTime data type
[ "", "sql", "sql-server", "datetime", "" ]
How can I find which part of the INSTR is not found? For example my query below returns 70002 and 70001 in my results. What I would now like to do is find which part is not in the table. Here is a hurdle I cant get over. I dont want to see all the other orderItems in the table. In my scenario here I just want 70000 re...
It would be better to parse the string into a `SecondTable` and get the desired results with: ``` select * from SecondTable where SecondTable.OrderItems not in(select OrderItems from Orders) ``` But if you need to select from the string, assign it to a variable and modify the variable for each record in your Orders t...
``` SELECT orderItems FROM Orders WHERE orderItems IN ('7001','7002','7003') SELECT orderItems FROM Orders WHERE orderItems NOT IN ('7001','7002','7003') ```
Finding which part of INSTR is not found
[ "", "sql", "" ]
I have a problem with a shell script: I am trying to inject data from a source file containing MySQL queries into a data base. Here are the relevant lines of my shell script: ``` mysql -u root source /usr/local/insert.sql; quit; ``` For example I am running the file as `./insertfile` and it is running smoothly but w...
Thanks for your help. I have tried adding your line in my script and it was primarily giving some errors then I changed the command like below - `mysql -u root --execute="source /usr/local/insert.sql; \q"` Above line helped me to execute my command. Thanks to all for being this much helpful. Regards, Shah9il
One way to do that would be ``` mysql -u root --execute="source /usr/local/insert.sql; quit;" ```
Inserting data in mysql with shell script
[ "", "mysql", "sql", "bash", "shell", "" ]
When we create parent-child tables, does the child table need its own primary key, or should the foreign key of the parent be used as the primary key? Example: I have a table that stores users, which is defined like: ``` CREATE TABLE users ( 'id' bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, 'username' varcha...
As a matter of principle, not related to other tables, each table should have a `PRIMARY KEY` in order for you to be able to distinguish one row from another. While it's not always necessary to absolutely identify individual rows that is often a requirement. In the event of a true one-to-one relationship (or a one-to-...
You have to understand the normalization rules. Here's the link <http://www.studytonight.com/dbms/database-normalization.php>.
Creating a parent and child table, does child need its own primary id column?
[ "", "mysql", "sql", "database", "relational-database", "" ]
I have a table CUSTOMER(ID,ADDRESS) with following values ``` 1,ROCKVILLE MDUS 2,JERSEY CITY NJUS 3,NEW YORK CITY NYUS . . . ``` I want to load the above values in separate table `STG_TXN(CITY,STATE,COUNTRY)`. Last two chars in `COUNTRY`, the second last two chars in `STATE` and everything before that in `CITY`. ``...
Try this: ``` INSERT INTO STG_TXN select SUBSTRING(address,0,LEN(address) - 4),SUBSTRING(address,LEN(address) - 3,2) ,SUBSTRING(address,LEN(address) - 1,2) from CUSTOMER ``` However, this only works if the the length of state or country is 2
This should work: ``` INSERT INTO STG_TXN select LEFT(@teststr,LEN(@teststr)-4) city, LEFT(RIGHT(@teststr,4),2) state, RIGHT(@teststr,2) country from customer ```
SQL Server : how to parse a column value and insert in multiple columns of separate table?
[ "", "sql", "sql-server", "parsing", "insert", "" ]
Say I have `student` table with a column `name`. This `name` column has values 'studentone', 'studenttwo', 'studentthree' & I want to replace them with 'student1', 'student2', 'student3'. For single replacement it's quite straight forward: ``` update student set name = replace(name, 'one', '1') ``` But what abou...
I would just use multiple update statements, but if you absolutely must do it in one statement, just nest the replace calls: ``` update student set name = replace(replace(replace(name, 'one', '1'), 'two', '2'), 'three', '3') ``` This works because (although inefficient) calls to `replace()` have no effect if the se...
While you *could* pack all into one statement, it would be inefficient without a matching **`WHERE` condition** to exclude unaffected rows. ``` UPDATE student SET name = replace(name, 'one', '1') WHERE name LIKE '%one'; UPDATE student SET name = replace(name, 'two', '2') WHERE name LIKE '%two'; UPDATE student SET name...
Use replace() function in an update to change more than one sub string of a column
[ "", "sql", "postgresql", "sql-update", "pattern-matching", "" ]
I am creating an event (like crone job) in MySQL to execute a query every 3 seconds but does not work. I tried my best. Here is my code please see if I am doing anything wrong ``` CREATE EVENT `croneJob` ON SCHEDULE EVERY 3 SECOND STARTS '2014-03-24 13:45:57' ON COMPLETION PRESERVE ENABLE DO insert into ranktable...
You have to start your MySQL server events scheduler: ``` SET GLOBAL event_scheduler = ON; ``` Loot at: <https://dev.mysql.com/doc/refman/5.1/en/events-configuration.html>
As I know all events are executed by a special event scheduler thread.When we refer to the Event Scheduler, we actually refer to this thread.There is global `event_scheduler` system variable determines whether the Event Scheduler is enabled and running on the server. Try to set the event\_Scheduler on your command lin...
Creating Event in MySQL does not work
[ "", "mysql", "sql", "" ]
I noticed that I can have NULL values in columns that have the UNIQUE constraint: `UNIQUE(col)` Would that generate any issues in certain situations?
While the following addresses multiple null values, it does *not* address any "issues" associated with such a design, other than possible database/SQL portability - as such, it should probably *not* be considered an answer, and is left here merely for reference. --- This is actually covered in the SQLite FAQ. It is a...
If you want your unique index to throw an error when a two rows would be the same if you disregard NULL columns (and don't want to use triggers from Satyam's answer) you can do something like this ``` CREATE TABLE `test` ( `Field1` INTEGER, `Field2` INTEGER ); CREATE UNIQUE INDEX `ix` ON `test` ( `Fi...
Sqlite NULL and unique?
[ "", "sql", "sqlite", "null", "unique", "unique-constraint", "" ]
I am trying to select distinct records to populate a select tag and I need the ids from the query but when I write a query like this: ``` Topic.select(:name).distinct ``` It comes back with results that look like this: ``` #<ActiveRecord::Relation [#<Topic id: nil, name: "Ruby">, #<Topic id: nil, name: "Python">, #<...
I think you want: ``` Topic.select('distinct on(name) id, name').order(:name) ```
For Rails 4.x, use ``` Topic.select(:id, :name).distinct ``` **NOTE:** To answer your question in comment i.e., > Nope that still returns repeat values if the same name was entered > twice You cannot do that. Suppose you have Python in two records then they'll have two different ids(as its primary key). Which id w...
How to I select distinct records with ids from a database in Rails?
[ "", "sql", "ruby-on-rails", "ruby-on-rails-4", "distinct", "" ]
I am thinking that this statement will and should pick the distinct values from my table and then also have a count of them or at least that is what I would like in a separate column. Is it possible to count the number of distinct values in SQL, from what I am gathering probably not. **Question: Can I count the number...
If I understand your question correctly, you want the result in two columns. If so, you can use **[Group By](http://www.w3schools.com/sql/sql_groupby.asp)**. ``` SELECT c.LastName as 'Distinct Last Names', COUNT(*) FROM Customer as c GROUP BY c.LastName ```
Since you donot have a `Group by` clause in the query, All your columns in the `Select` should use some kind of an aggregation or else `SQL` will not be happy. Try this ``` select COUNT(distinct c.LastName) 'Distinct Last Names' from Customer as c; ```
Is it possible in SQL to count the number of distinct values as well?
[ "", "sql", "" ]
I have a table `author_data`: ``` author_id | author_name ----------+---------------- 9 | ernest jordan 14 | k moribe 15 | ernest jordan 25 | william h nailon 79 | howard jason 36 | k moribe ``` Now I need the result as: ``` author_id | author_name ...
I suggest a [window function](https://www.postgresql.org/docs/current/functions-window.html) in a subquery: ``` SELECT author_id, author_name -- omit the name here if you just need ids FROM ( SELECT author_id, author_name , count(*) OVER (PARTITION BY author_name) AS ct FROM author_data ) sub WHERE...
You are half way there already. You need to just use the identified `Author_IDs` and fetch the rest of the data. try this.. ``` SELECT author_id, author_name FROM author_data WHERE author_id in (select author_id from author_data group by author_name having count(author_name)>1) ```
Find rows with duplicate values in a column
[ "", "sql", "postgresql", "duplicates", "aggregate-functions", "window-functions", "" ]
Eg, take this **ACCOUNT** table: ``` |num | type |amount| |---------------------- | 1 | cheque | 300 | | 2 | cheque | 300 | | 2 | savings | 300 | ``` Would **[type, amount]** by a primary key even though **[cheque, 300]** appears twice? I'm confused because even though cheque 300 is duplicated, the **num*...
No, [type, amount] cannot be primary key, because it is not unique. There are two ways to work with primary keys in a database: 1. Work with technical IDs. You simply add an ID column to your tables and only link by these. 2. Work with natural keys. That would be the ISBN for a table of books for instance or the empl...
If `num` is the primary key, then it cannot contain duplicates or NULL values. "Primary key" implies no duplication. It's conceivable that you could have a composite primary key consisting of `(id, type)`. That might make sense in an application where a particular `id` could have both a checking and a savings account ...
Can primary keys themselves contain duplicates but have unique rows?
[ "", "mysql", "sql", "" ]
``` update accounts set password=(select password from accounts where name='joongsu') where id=(select accountid from characters where name='Nobless') ``` it doesn't work with error message "You can't specify target table 'accounts' for update in FROM clause" Why doesn't it work? select queries in above only return ...
Perhaps you should try [this one](https://stackoverflow.com/a/14302701/3416826): ``` UPDATE accounts SET accounts.password = ( SELECT something.password FROM (SELECT * FROM accounts) AS something WHERE something.name='joongsu' ) WHERE accounts.id=(SELECT accountid FROM characters WHERE name='Nobless'); ```...
``` UPDATE accounts AS account_to_be_updated JOIN characters ON characters.accountid = account_to_be_updated.id AND characters.name = 'Nobless' CROSS JOIN ( SELECT password FROM accounts WHERE name = 'joongsu' ) AS existing_account SET account_to_be_updated.passwor...
How to use data in same table on UPDATE query?
[ "", "mysql", "sql", "" ]
For the following data in a table, I want to get the highest balance for each person and then sort the result in descending order of that highest balance: ``` |---------id--------|--------name--------|--------balance-------- 1 | Tom | 10 2 | Bob |...
maybe like this: ``` select pid, name, max(balance) as highest_balance from my_table group by pid, name order by max(balance) desc; ```
You can use `MAX()` and order by ``` SELECT id,name,MAX(balance) AS balance FROM table GROUP BY name ORDER BY balance DESC ``` ## [Fiddle](http://sqlfiddle.com/#!2/198f00/4)
How to use the highest values for a certain criteria to sort the list?
[ "", "mysql", "sql", "" ]
I am not sure, but I think I have an error in this query: ``` UPDATE product_discount SET price = '10,15' WHERE key_id = '1,2' ``` I can't figure out why, but it only updates number 10 in the column and skips the 15.
You could try the method suggested in [this answer](https://stackoverflow.com/a/3466/2359271): ``` INSERT INTO product_discount (key_id, price) VALUES (1, 10), (2, 15) ON DUPLICATE KEY UPDATE price=VALUES(price); ``` Be sure to read the linked answer for some caveats, though; for example, this only works if: * Ther...
I think this is what you need (Assuming `Price` should be 10 when `key_id = 1`): ``` UPDATE product_discount SET price = CASE WHEN key_id = 1 THEN 10 ELSE 15 END WHERE key_id IN (1,2) ```
MySQL Table won't update multiple rows
[ "", "mysql", "sql", "sql-update", "" ]
I have a column `eventDate` which contains trailing spaces. I am trying to remove them with the PostgreSQL function `TRIM()`. More specifically, I am running: ``` SELECT TRIM(both ' ' from eventDate) FROM EventDates; ``` However, the trailing spaces don't go away. Furthermore, when I try and trim another character f...
There are many different invisible characters. Many of them have the property `WSpace=Y` ("whitespace") in Unicode. But some special characters are not considered "whitespace" and still have no visible representation. The excellent Wikipedia articles about [space (punctuation)](https://en.wikipedia.org/wiki/Space_%28pu...
It should work the way you're handling it, but it's hard to say without knowing the specific string. If you're only trimming leading spaces, you might want to use the more concise form: ``` SELECT RTRIM(eventDate) FROM EventDates; ``` This is a [little test](http://sqlfiddle.com/#!15/c2f73/387) to show you that it ...
Trim trailing spaces with PostgreSQL
[ "", "sql", "postgresql", "whitespace", "trim", "removing-whitespace", "" ]
I have a collection in MongoDB with such data: ``` sid; geo -------- 4; 100 4; 101 2; 100 2; 106 2; 107 1; 100 1; 100 1; 100 1; 110 1; 100 ``` How to do such SQL query in MongoDB? ``` SELECT sid COUNT(DISTINCT geo) FROM sites GROUP BY sid ``` I want to have a collection with count of unique geo for every sid: ``` ...
Distinct is a type of grouping indeed but the output equivalent of that type of query is this: ``` db.collection.aggregate([ { "$group": { "_id": { "sid": "$sid", "geo": "$geo" } }}, { "$group": { "_id": "$_id.sid", "geo_count": { "$sum": 1 } }} ]} ``` So you need to first grou...
Since DISTINCT is actually a type of group you can do: ``` db.c.aggregate({ {$group: {_id: '$geo', sid: '$sid', 'geo_sum': {$sum: 1}}}, {$group: {_id: '$sid', 'geo_count': {$sum: 1}}} }) ```
How to do distinct and group in MongoDB Aggregation Framework?
[ "", "sql", "mongodb", "" ]
``` $query = "SELECT table1.first_name, table1.id, table1.profile_image FROM table1,table2 WHERE table1.id = ( CASE WHEN '$id' = table2.id1 THEN ...
You know the right syntax for a case construction is: ``` CASE WHEN ... THEN .... WHEN ... THEN .... ELSE ... END ``` Notice the `END` at the .... end ;)
``` Select first_name, id, profileImage From Table1 inner join ( Select id1 as t2id From Table2 where `case` = 'done' union Select id2 From Table2 Where `case` = 'done') t2Ids ) On Table1.id = t2Ids.t2id Where t2Ids.t2Id = $id ``` Would be another way to do it.
Can't figure error in a mysql query
[ "", "mysql", "sql", "" ]
I'm trying to find a way to combine two columns into one, but keep getting the value '0' in the column instead to the combination of the words. These are what I've tried as well as others: ``` SELECT column1 + column2 AS column3 FROM table; SELECT column1 || column2 AS column3 FROM table; SELECT column1 + ' ' + col...
My guess is that you are using MySQL where the `+` operator does addition, along with silent conversion of the values to numbers. If a value does not start with a digit, then the converted value is `0`. So try this: ``` select concat(column1, column2) ``` Two ways to add a space: ``` select concat(column1, ' ', col...
Try this, it works for me ``` select (column1 || ' '|| column2) from table; ```
MySQL combine two columns into one column
[ "", "mysql", "sql", "" ]
I need a table where CHECK will check if values are ordered in the same way (are monotonic). For example: ``` CREATE TABLE test ( ID int identity primary key, ID_foreignkey int references something, order int, value int ) ``` I need effect that for the same ID\_foreign key, order grows and also value ...
If we can force `order` to start at 1 and to have no gaps, then we can achieve *most* of the requirements declaratively: ``` CREATE TABLE test ( ID int not null identity, ID_foreignkey int not null, [order] int not null, value int not null, prev_order as CASE WHEN [order] > 1 THEN [order]-1 END per...
you can create a function like this that return the next value expected ``` create FUNCTION [dbo].[test](@id integer, @typeKey integer) RETURNS int AS BEGIN DECLARE @retval int if @typeKey=1 begin SELECT @retval = max([order]) + 1 FROM table where ID_foreignkey = @id end else begin /*ne...
SQL Server: values in two columns must be monotonic
[ "", "sql", "sql-server", "constraints", "" ]
I have a MySQL table like this: ![](https://i.stack.imgur.com/FMYyi.png) And I want to convert it from long format to wide format like this ![](https://i.stack.imgur.com/IFqnm.png) Sorry. I'm new and don't know how to post a table
Try this: ``` insert into goodTable select bt.id, (select bt1.value from badTable bt1 where bt1.info = 'firstname' and bt1.id = bt.id), (select bt1.value from badTable bt1 where bt1.info = 'lastname' and bt1.id = bt.id), (select bt1.value from badTable bt1 where bt1.info = 'phone' and bt1.id = bt.id) from badTable b...
You need something like this: ``` select id, max(case when info='firstname' then value else null end), max(case when info='lastname' then value else null end), ... from table group by id; ```
Mysql convert table from long format to wide format
[ "", "mysql", "sql", "pivot", "database-table", "" ]
I just saw the weirdest thing ever in some very old SQL code we have. There is a multiply equals operator in a where clause. Does it have a special meaning? It selects the appropriate columns, but `o.name` is `NULL`. I am sure it is a typo, but I just want to confirm. ``` select c.name, c.status, o....
This question was already answered here: [SQL Server \*= Operator?](https://stackoverflow.com/questions/983862/sql-server-operator) Beyond being the oldschool way, as fancyPants mentioned, it also may not always work consistently. You should revise your SQL statement to include the JOINS in the FROM clause. To answer...
As mentioned, this is a `LEFT OUTER JOIN`. Similarly, =\* is a `RIGHT OUTER JOIN` That said, it shouldn't be used anymore, and you should use the full syntax.
SQL Multiply Equals (*=) in a WHERE clause
[ "", "sql", "" ]
In toad's older version i can easily able to format the query in Toad's Query editor by ``` right click > Format Code. ``` But in newer version of Toad 7 i can't able to find this Format option. Can any one help me from where i can Format My Query. (**how to FORMAT QUERY in TOAD 7?**)
**TOAD FOR ORACLE** `SHIFT`+`CTRL`+F should help you To format a statement Select the statement you want to select and click `»` on the Edit toolbar. To format an entire script Click `»` on the Edit toolbar. **Tip**:You can also right-click the script and select Formatting Tools | Format Code. See the [documentati...
Just to add, in Toad 5 for SQLServer, the button to format code is "2 yellow triangles pointing right". In my fresh installation, this button is on the toolbar, beside the dropdown box to select the db environment. If you want to assign a shortcut, find it at Tools | Options | Environment | Keyboard | Editor | Tools |...
Format sql query in TOAD 7.
[ "", "sql", "format", "toad", "" ]
I am trying to find the most used query in an oracle database.. Im a little confused! Are these types of statistics stored in the AWR table? If so how would I use this table to find the most popular query executed on the database? Thanks!
try this: ``` SELECT ADDRESS, SQL_TEXT, PARSE_CALLS, EXECUTIONS FROM V$SQLAREA ORDER BY EXECUTIONS desc; ```
That might be fast on many systems one system I was on last week took > 3 minutes to execute a query like this. To make it more efficient, it's cheaper to select from v$sqlstats. thatn v$sqlarea. Also since you are doing an order by you might want to limit the rows sorted with something like "executions > X" select \*...
Find most frequently used query
[ "", "sql", "database", "oracle", "statistics", "" ]
The following query is giving an error at 'CASE WHEN NOT LIKE' (Msg 156, Level 15, State 1, Line 14 Incorrect syntax near the keyword 'LIKE') ``` SELECT TimeStamp, TimeStampNS, ISNULL(TagName, 'NoTag') AS TagName, Message, ConditionName, ISNULL(TagName, 'NoTag') + '.' + ConditionName AS Source, CENTU...
I think you missed the attribute name here: ``` CASE WHEN <ATTRIBUTE-NAME> NOT LIKE '% ACK%' AND CENTUMMsgId IN (4353, 4355, 4609) THEN 1 ELSE 0 END AS RaiseAll, CASE WHEN <ATTRIBUTE-NAME> LIKE '% ACK%' THEN 1 ELSE 0 END AS Acknowledge, CASE WHEN CENTUMMsgId ... ```
``` CASE WHEN **[MissingExpression]** NOT LIKE '% ACK%' AND CENTUMMsgId IN (4353, 4355, 4609) THEN 1 ELSE 0 END AS RaiseAll, CASE WHEN **[MissingExpression]** LIKE '% ACK%' THEN 1 ELSE 0 END AS Acknowledge, CASE WHEN CENTUMMsgId IN (4354, 4356, 4358, 4614) AND Message NOT LIKE '% ACK%' THEN 1 ELSE 0 END AS Normal, P...
SQL Query - Incorrect syntax near the keyword 'LIKE'
[ "", "sql", "sql-server-2008", "" ]
By see below tables how to (write query) get `Table A` data and `status = InActive` with no Data in `Table B` Example : `4 Comm4 InActive` ``` Table A AID Name Status -- --- -- 1 comm1 Active 2 comm2 Active 3 Comm3 InActive 4 Comm4 InActive 5 ...
It's quite simple ``` select * from tableA where status = 'InActive' and not exists (select * from tableB where tableA.AID = tableB.AID) ```
``` select tableA.* from tableA left join tableB on tableA.AID = tableB.AID and tableA.status = 'InActive' where tableB.AID is null ``` The not exists from Szymon is correct and may be more efficient
Finding data from Table A and Table B relation
[ "", "sql", "sql-server", "t-sql", "" ]
Consider the DB : Account table ![enter image description here](https://i.stack.imgur.com/0wKzt.gif) With the records : ![enter image description here](https://i.stack.imgur.com/7Raba.gif) Clients table ![enter image description here](https://i.stack.imgur.com/lUvtP.gif) with the records : ![enter image descrip...
**UPDATE:** Firstly, I should make clear the following, you dont need to use the "group by" because you are not summarizing, so your query should be: ``` SELECT c.Client_id_number , a.Account_number , c.firstName_client , c.lastName_Client , a.Account_balance FROM Clients AS c INNER JOIN Accounts AS a ON a.Client_id...
You are only grouping by `client_id_number`, which means you will only get one row per client ID. You need to group by *the set of rows that you want to be unique in the output*. In this case, that probably means: ``` GROUP BY c.Client_id_number, a.account_number ``` And then you should apply an aggregate function t...
GROUP BY doesn't return all rows per specific field
[ "", "mysql", "sql", "" ]
What is the best way for querying this in ORMLite? ``` SELECT JOB.TASK_JOB, JOB.NAME_JOB, JOB_SETTINGS.DAY1, JOB_SETTINGS.DAY2, JOB_SETTINGS.DAY3, JOB_SETTINGS.DAY4, JOB_SETTINGS.DAY5, JOB_SETTINGS.DAY6, JOB_SETTINGS.DAY7, ...
You can use queryRaw() method of your Dao. For example ``` GenericRawResults<String[]> rawResults = queryDao.queryRaw("SELECT JOB.TASK_JOB, JOB.NAME_JOB, JOB_SETTINGS.DAY1, JOB_SETTINGS.DAY2, JOB_SETTINGS.DAY3, JOB_SETTINGS.DAY4, ...
This has nothing to do with ORMLite, but there's a really handy tool for doing query, right in SQLiteQueryBuilder. You can do this: ``` private static final String COLS = new String[] { JOB.TASK_JOB, JOB.NAME_JOB, JOB_SETTINGS.DAY1, JOB_SETTINGS.DAY2, JOB_SETTINGS.DAY3, JOB_SETTINGS.DAY4, J...
How to build a Select query (more tables without join) in ORMLite
[ "", "android", "sql", "select", "join", "ormlite", "" ]
How To Fetch records from a table ? But only those records which `added_on >= '2014/03/01'` and `added_on <= '2014/03/31'` and currently my sql table field value is `added_on = 2014/03/29 05:23:43` Please help me out as soon as possible
simple SQL Query ``` select * from table_name where (added_on between '2014-03-01' and '2014-03-31' ); ``` You may also want to specify `hh:mm:ss` ``` select * from table_name where (added_on between '2014-03-01 00:00:00' and '2014-03-31 00:00:00' ); ``` Both should work. :)
``` SELECT * FROM [table] WHERE CONVERT(datetime, [added_on]) between '2014/03/01' AND '2014/03/31' ```
How to Fetch Records from table in Sql between two dates
[ "", "mysql", "sql", "" ]
I have a master table in sql server 2012 that consists of two types. These are the critical columns I have in my master table: ``` TYPE CATEGORYGROUP CREDITORNAME DEBITORNAME ``` One of those two types (Type B) doesn't have a CategoryGroup assigned to it (so it's always null). Type A always has a CategoryGr...
If I understand you correctly, you can simply do a join to find the correct value, and update MainData with that value; You can either use a common table expression... ``` WITH cte AS ( SELECT a.*, b.categorygroup cg FROM MainData a JOIN CreditorList b ON a.creditorname = b.creditorname ) UPDATE cte SET cat...
Couldn't you just do: ``` update maindata set categorygroup = ( select top 1 categorygroup from creditorlist where creditorname = maindata.creditorname) where creditorname is not null and categorygroup is null ``` ?
TSQL - Insert values in table based on lookup table
[ "", "sql", "sql-server", "t-sql", "lookup", "" ]
All my column headers in a MySQL database are prefixed with a number, 1\_X, 2\_X, etc... which makes bringing the data into IDL impossible using just a basic select statement to bring in the entire table. I'm not sure but I see two possible ways: 1) Bring in the table with column name aliases. Can I use TRIM or SUBSTR...
It's not possible to use functions in a SQL statement to alter the identifier assigned to a column being returned. The SQL way of specifying the identifier for the column in a resultset is to use the `expr AS alias` approach. --- Rather than trim off the leading digit characters, you could prepend the identifiers wit...
I think you can follow option 2. However this will not be quick solution. Another way around this could be, > 1. Generate schema script for the tables you want to correct. > 2. Open the script in notepad++ or any editor that supports find using regular expression. > 3. Search and replace with [0-9]+\_ expression and ...
MySQL Remove characters from column headers
[ "", "mysql", "sql", "rename", "idl", "" ]
**My error is as follows:** > Cannot insert explicit value for identity column in table 'Snacks' when IDENTITY\_INSERT is set to OFF. > Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originate...
This is not specifically an ASP.NET issue, it's a SQL error. When you have an `identity` column, every time a new row is added, that column should contain a new value (normally incremented by 1). The error your showing is because either you or the technology you're using is attempting to tell SQL Server what value sh...
you need to SET IDENTITY\_INSERT ON: Syntax is: ``` SET IDENTITY_INSERT [ database_name . [ schema_name ] . ] table { ON | OFF } ```
ASP.NET: Identity_Insert set to OFF - How do I fix this?
[ "", "sql", "sql-server", "" ]
I'm trying to manually execute SQL commands so I can access procedures in NuoDB. I'm using Ruby on Rails and I'm using the following command: ``` ActiveRecord::Base.connection.execute("SQL query") ``` The "SQL query" could be any SQL command. For example, I have a table called "Feedback" and when I execute the comm...
The working command I'm using to execute custom SQL statements is: ``` results = ActiveRecord::Base.connection.execute("foo") ``` with "foo" being the sql statement( i.e. "SELECT \* FROM table"). This command will return a set of values as a hash and put them into the results variable. So on my rails application\_c...
For me, I couldn't get this to return a hash. ``` results = ActiveRecord::Base.connection.execute(sql) ``` But using the exec\_query method worked. ``` results = ActiveRecord::Base.connection.exec_query(sql) ```
How do you manually execute SQL commands in Ruby On Rails using NuoDB
[ "", "sql", "ruby-on-rails", "activerecord", "nuodb", "" ]
I'm fairly new to SQL (~9 months or so) and so I'm stumped trying to figure out this problem, using SQL Server 2012. I'm trying to match up two tables that look like this: Table `Shift`: ``` Date | Name | Shift 01-01-2013 | Dan Smith | Night 01-02-2013 |John Johnson| Night 01-03-2013 |Jo...
Ok, this works as you intended: ``` ;WITH Sales2 AS ( SELECT A.*, CASE WHEN B.[Date] IS NULL THEN 1 ELSE 0 END LastShift FROM Sales A LEFT JOIN Sales B ON A.Name = B.Name AND A.[Date] = DATEADD(DAY,-1,B.[Date]) ) SELECT A.[Date], A.Name, A.Shift, SUM(B.Sales) Sales FROM...
I think you might need a better model. See if this works? ``` SELECT sft.Name, sft.Date, sft.Shift, sum(sls.Sales) FROM Sales sls LEFT JOIN Shift sft ON sls.Date >= sft.Date WHERE (sls.Date = sft.Date OR sls.Date NOT IN (SELECT Date FROM Shift WHERE Date = sls.Date AND Name = ...
Need to match two SQL tables based on dates but I need to check for date+1
[ "", "sql", "sql-server", "date", "" ]
my SQL is a bit rusty after 2 years of not having studied it, so I can't find a way to do this. I need to get some data from a Moodle database, namely some averages of feedback tests where students rate their teachers. This SQL query: ``` SELECT mdl_course.id, mdl_user.username FROM mdl_course INNER JOIN mdl_context...
If you take each of the subqueries and then try to JOIN them, it should work. I added a third field to help you see the detail of how the score was created. ``` SELECT username, AVG(average) AS average , GROUP_CONCAT(CONCAT('Course: ', teachers.course_id,' with score ', COALESCE(average,'No Score Found'))) AS detail...
I am Trying to use a temp table to store the two different query result sets and then later i am querying the temp table to get the average of the teacher. Hope this works. ``` CREATE TABLE #TEMP ( COURSE_ID int, TEACHER varchar(100), COURSE int, AVERAGE int ) --- Inserting the course_id and Teahcer data---- INSERT I...
Merging 2 SQL queries with a common field and AVGs
[ "", "mysql", "sql", "join", "merge", "moodle", "" ]
Hello here's my question Retrieve the total number of bookings for each type of the services that have at least three bookings (excluding those cancelled). i.e. where status = 'open' AND 'done' I'm not to sure on how to exclude and how to count values in a column? ``` SELECT Service.type, Service.description, COUN...
It will be faster to aggregate first and join later. Fewer join operations. Hence the subquery: ``` SELECT s.type, s.description, b.ct FROM ( SELECT service, count(*) AS ct FROM booking WHERE status <> 'cancelled' GROUP BY 1 HAVING count(*) > 2 ) b JOIN service s ON s.type = b.service; ``` Sinc...
``` select s.type, s.description, count(*) from booking b inner join service s on b.service = s.type where status != 'cancelled' group by 1, 2 having count(*) >= 3 order by 3 desc; ```
SQL COUNT EXCLUDE
[ "", "sql", "postgresql", "join", "count", "aggregate-functions", "" ]
I used to do Oracle development many many years ago. I have spent most of the past 15 years doing mainly SQL Server, and where I have done Oracle work, been insulated from the workings by Web services etc. My question seems to have been asked on the web a few times, but it seems difficult somehow to communicate - at l...
With [SQL Developer](http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index-097090.html) or SQL\*Plus you can use a bind variable declared before the PL/SQL block: ``` variable rc refcursor; declare my_id number := 356655; begin open :rc for select my_id from dual; end; / print rc RC ---...
I use [Oracle SQL Developer](http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index-097090.html). Anyway, this should work in any oracle sql client: If you just want to see your results, you can use ``` dbms_output.put_line('Foo' || somevar || ' bar'); ``` Before this, run ``` SET SERVEROU...
Ad hoc querying Oracle PL/SQL - for SQL Server developer
[ "", "sql", "oracle", "plsql", "database-tools", "" ]
I found a sproc in a db that I think infers a table join? Is that accurate to deduce that from the sample below? ``` SELECT a.Column1, b.Column2 FROM [dbo].[Table1] As a, [dbo].[Table2] AS b ```
It does infers a join, but that join is a `CROSS JOIN`, which is rarely what you want. It won't simply map each row of `a` to its equivalent in `b`. Instead, it will map each row of `a` to every row of `b`. That is a join, but it's not what we often think of when we talk about joins. I wanted to show a quick example, ...
You inferred correctly, this is a Cartesian join.
when selecting from multiple SQL Server 2008 tables is a join inferred?
[ "", "sql", "sql-server-2008", "" ]
There are 3 tables: `Students`, `Courses` and `Grades`. `sid`, `cid` and `sid-cid`(Super key) are the primary keys of each table. `Students`: ``` sid sname address ----------------- S1 Adam Abawama S2 Mery Ignora S3 Aisha Icterra S4 Sello Icterra S5 Mery Kaysers ``` `Courses`: ``` cid cname dept -------...
I like to use TDQD — Test-Driven Query Design. You build up the query in stages, validating each stage. This is a fairly simple query to do — it only needs two steps (though arguably I've compressed two steps into step 2). ### Step 1 You need to do a self-join in some shape or form. This query lists students (by `sid...
Another approach is to use two correlated subqueries, like so: ``` select S.SNAME from STUDENTS S where exists (select G1.SID from GRADES G1 inner join COURSES C1 on G1.CID=C1.CID where G1.SID = S.SID and C1.DEPT = 'Ceng') and exists (select G2.SID from GRADE...
How to translate SQL to Relational Algebra on Relational Database Tables
[ "", "sql", "sql-server-2008", "relational-database", "relational-algebra", "" ]
``` CREATE TABLE info(id KEY AUTO_INCREMENT, email VARCHAR(20), name VARCHAR(20)); ``` While using this code, in Ubuntu terminal, i am getting error like below > ERROR 1064 (42000): You have an error in your SQL syntax; check the > manual that corresponds to your MySQL server version for the right > syntax to use ne...
try this: ``` CREATE TABLE info( id int not null AUTO_INCREMENT, email VARCHAR(20), name VARCHAR(20), primary key(id) ); ```
Try that: ``` CREATE TABLE info(id INT NOT null AUTO_INCREMENT, email VARCHAR(20), name VARCHAR(20),primary key(id)); ```
Syntax error in MySQL check manual
[ "", "mysql", "sql", "terminal", "" ]
Let's say we have a database that records all the Movies a User has not rated yet. Each rating is recorded in a MovieRating table. When we are looking for movies user #1234 hasn't seen yet: ``` SELECT * FROM Movies WHERE id NOT IN (SELECT DISTINCT movie_id FROM MovieRating WHERE user_id = 1234); ``` Querying ...
A correlated sub-query using WHERE NOT EXISTS() is potential your most efficient if you have to do this, but you should test performance against your data. You may also want to consider limiting your results both in terms of the select list (don't use \*) and only getting TOP n rows. That is, you may not need 100k+ mo...
This is a mock query, because I don't have a db to test this, but something along the lines of the following *should* work. ``` select m.* from Movies m left join MovieRating mr on mr.user_id = 1234 where mr.id is null ``` That should join the movies table to the movie rating table based on a user id. The where claus...
What are some alternatives to a NOT IN query?
[ "", "sql", "database", "performance", "" ]
I was wondering if there is anyway to count the number of days in a month in SQL server 2008... Something similar to this Javascript code I wrote: ``` function daysInMonth(month, year) { return new Date(year, month, 0).getDate(); } var dateForApp = new Date(); ...
A recursive CTE can provide a days table; ``` declare @date datetime = '01 feb 1969' declare @days int = datediff(day, dateadd(day, 1 - day(@date), @date), dateadd(month, 1, dateadd(day, 1 - day(@date), @date))) ;with days(day) as ( select 1 as day union all select day + 1 ...
Have you tried using [DATEDIFF](https://stackoverflow.com/questions/691022/how-to-determine-the-number-of-days-in-a-month-in-sql-server)?
Count days of month
[ "", "sql", "sql-server", "" ]
I have a bit problem returning the max value of a group using mysql this is my columns ``` id | date | time | tran --------+----------------+----------+---------- 1 | 2014/03/31 | 17:23:00 | 1234 1 | 2014/03/31 | 17:24:00 | 3467 2 | 2014/03/31 | 17:26:00 | 2345 ``` My...
You can do this by using self join on the maxima from same table ``` SELECT t.* FROM Table1 t JOIN ( SELECT id, max(date) date, MAX(time) time , tran FROM Table1 GROUP BY id) t2 ON(t.id=t2.id AND t.date=t2.date AND t.time=t2.time) ``` ## [Fiddle](http://sqlfiddle.com/#!2/a75d9/1) There may be differences between max...
There is a great article on this theme which a read every time i am facing your problem. You might want to c[heck it](http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/) Applying to you query, this will look like: ``` SELECT * FROM `table` WHERE ( SELECT count(*)...
MYSQL returning the max value per group
[ "", "mysql", "sql", "greatest-n-per-group", "" ]
I have a huge table where a new row could be an "adjustment" to a previous row. TableA: ``` Id | RefId | TransId |Score ---------------------------------- 101 | null | 3001 | 10 102 | null | 3002 | 15 103 | null | 3003 | 15 104 | 101 | | -5 105 | null | 3...
try this: ``` select sum(sum1 + sums) as sum_all from ( SELECT t1.id,T1.Score sum1, coalesce(T2.score,0) sums FROM Table1 t1 inner JOIN Table2 ON T1.TransId=Table2.TransId left JOIN Table1 t2 ON t2.RefId = t1.id WHERE Table2.Person='Harry' )c ``` [**DEMO HERE**](http://sqlfid...
``` Select sum(total) AS total From tableb Join ( Select t1.transid, sum(score) AS total From tablea t1 Join tablea t2 on t1.id = t2.refid group by t1.transid ) x on x.transid = tableb.transid Where TableB.Person='Harry' ```
Sum Log values from table using second table
[ "", "mysql", "sql", "" ]
I understand that this has been asked already. However, I am relatively new at SQL and MySQL, so I was confused by the other answers. Say I have a table of historical financial data, and I have multiple records in place. ``` Date | Close Price | % Change 2014-03-25 | 3.58 | ? 2014-03-24 | 3.57 |...
Something like this would do it I think ``` SELECT x.Date, x.Close_Price, (((x.Close_Price / y.Close_Price) - 1) * 100) AS '% Change' FROM ( SELECT a.Date AS aDate, MAX(b.Date) AS aPrevDate FROM SomeTable a INNER JOIN SomeTable b WHERE a.Date > b.Date GROUP BY a.Date ) Sub1 INNER JOIN SomeTable x ...
``` Select S1.Date as Today, (S1.ClosePrice - S2.ClosePrice) / S2.ClosePrice as Change FROM Stock as S1 INNER JOIN Stock as S2 ON S1.Date = (S2.Date+1) ```
Calculating Percent Change between two rows
[ "", "sql", "" ]
I'm trying to implement a FIFO queue using a sql table. I have the following SQL (modified for posting), the join and param usage are important to the way this process works. ``` With cte as ( select top(1) q.* from queue q with (readpast) inner join MyTable a on q.id = a.myTableID AND myTable.procID = @myParam...
You can use `exists()` instead of the inner join to `MyTable` in the CTE. ``` with cte as ( select top(1) q.id, q.col1 from queue q with (readpast) where exists( select * from MyTable a where q.id = a.myTableID AND a.procID = @my...
Something like this? ``` With cte as ( select top(1) q.* from queue q with (readpast) inner join MyTable a on q.id = a.myTableID AND myTable.procID = @myParam order by q.Data asc ) delete from queue Where ID in (Select Id from cte) ```
Delete from CTE with join
[ "", "sql", "sql-server", "t-sql", "common-table-expression", "dml", "" ]
i have two tables ``` activity id | user_id | time | activity_id 1 | 1 | | 3 2 | 1 | | 1 and preferences user_id | running | cycling | driving 1 | TRUE | FALSE | FALSE i need result set of id | user_id | time | 2 | 1 | | ``` i only need rows from first table whose...
If you can edit the schema, it would be better like this: ``` activity id | name 1 | running 2 | cycling 3 | driving user_activity id | user_id | time | activity_id 1 | 1 | | 3 2 | 1 | | 1 preferences user_id | activity_id 1 | 1 ``` A row in preferences indicates a `TRUE` value f...
What I would probably do is join the tables on a common column, looks like `user_id` is a common column in this case, which gives access to the columns in both tables to query against in the where clause of the query. Which type of join depends on what information you want from preferences [Handy Visual Guide for joi...
select statement with only rows which have set true in second table
[ "", "mysql", "sql", "" ]
how to select data between 2 dates in between 2 dates? for example : ``` start_date - end_date -- title 2014-01-28 2014-02-03 test 2014-02-01 2014-02-15 ests 2014-02-28 2014-03-03 sets 2014-03-01 2014-03-10 sste ``` the problem is, i want to select data between 2014-02-02 and 2014-02-28 with first three of them s...
Two periods overlap when one begins before the other ends, and the other ends after the first begins. Here is the correct logic: ``` SELECT title FROM my_tables WHERE start_date <= '2014-02-28' and end_date >= '2014-02-02'; ``` Note that date constants need to be in single quotes. [Here](http://www.sqlfiddle.c...
A date range overlaps with another when either the start or the end is within that other range: ``` given range: |----| range 1 |----| overlaps with given range, because end_date is in that range range 2 |----| overlaps with given range, because start_date is in that range range 3 |----...
Mysql Between in Between
[ "", "mysql", "sql", "between", "" ]